aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.config/dotnet-tools.json2
-rw-r--r--.github/ISSUE_TEMPLATE/issue report.yml9
-rw-r--r--.github/workflows/ci-codeql-analysis.yml6
-rw-r--r--.github/workflows/ci-compat.yml6
-rw-r--r--.github/workflows/ci-openapi.yml12
-rw-r--r--.github/workflows/ci-tests.yml2
-rw-r--r--.github/workflows/commands.yml2
-rw-r--r--.github/workflows/issue-template-check.yml2
-rw-r--r--.github/workflows/pull-request-conflict.yml2
-rw-r--r--CONTRIBUTORS.md2
-rw-r--r--Directory.Packages.props81
-rw-r--r--Emby.Naming/Common/NamingOptions.cs3
-rw-r--r--Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs46
-rw-r--r--Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs1
-rw-r--r--Emby.Server.Implementations/ApplicationHost.cs55
-rw-r--r--Emby.Server.Implementations/Chapters/ChapterManager.cs313
-rw-r--r--Emby.Server.Implementations/Collections/CollectionManager.cs8
-rw-r--r--Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs38
-rw-r--r--Emby.Server.Implementations/Dto/DtoService.cs30
-rw-r--r--Emby.Server.Implementations/Emby.Server.Implementations.csproj6
-rw-r--r--Emby.Server.Implementations/IO/FileRefresher.cs2
-rw-r--r--Emby.Server.Implementations/IO/LibraryMonitor.cs2
-rw-r--r--Emby.Server.Implementations/IO/ManagedFileSystem.cs7
-rw-r--r--Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs4
-rw-r--r--Emby.Server.Implementations/Library/DotIgnoreIgnoreRule.cs77
-rw-r--r--Emby.Server.Implementations/Library/ExternalDataManager.cs58
-rw-r--r--Emby.Server.Implementations/Library/IgnorePatterns.cs1
-rw-r--r--Emby.Server.Implementations/Library/KeyframeManager.cs44
-rw-r--r--Emby.Server.Implementations/Library/LibraryManager.cs249
-rw-r--r--Emby.Server.Implementations/Library/MediaSourceManager.cs22
-rw-r--r--Emby.Server.Implementations/Library/PathManager.cs75
-rw-r--r--Emby.Server.Implementations/Library/ResolverHelper.cs20
-rw-r--r--Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs3
-rw-r--r--Emby.Server.Implementations/Library/SplashscreenPostScanTask.cs13
-rw-r--r--Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs69
-rw-r--r--Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs157
-rw-r--r--Emby.Server.Implementations/Library/Validators/CollectionPostScanTask.cs217
-rw-r--r--Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs69
-rw-r--r--Emby.Server.Implementations/Library/Validators/GenresValidator.cs136
-rw-r--r--Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs69
-rw-r--r--Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs117
-rw-r--r--Emby.Server.Implementations/Library/Validators/PeopleValidator.cs181
-rw-r--r--Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs69
-rw-r--r--Emby.Server.Implementations/Library/Validators/StudiosValidator.cs151
-rw-r--r--Emby.Server.Implementations/Localization/Core/af.json8
-rw-r--r--Emby.Server.Implementations/Localization/Core/ar.json4
-rw-r--r--Emby.Server.Implementations/Localization/Core/de.json40
-rw-r--r--Emby.Server.Implementations/Localization/Core/gl.json14
-rw-r--r--Emby.Server.Implementations/Localization/Core/he.json8
-rw-r--r--Emby.Server.Implementations/Localization/Core/he_IL.json1
-rw-r--r--Emby.Server.Implementations/Localization/Core/lzh.json7
-rw-r--r--Emby.Server.Implementations/Localization/Core/mr.json9
-rw-r--r--Emby.Server.Implementations/Localization/Core/ms.json34
-rw-r--r--Emby.Server.Implementations/Localization/Core/nb.json4
-rw-r--r--Emby.Server.Implementations/Localization/Core/pt-PT.json6
-rw-r--r--Emby.Server.Implementations/Localization/Core/pt.json4
-rw-r--r--Emby.Server.Implementations/Localization/Core/sq.json12
-rw-r--r--Emby.Server.Implementations/Localization/Core/ta.json6
-rw-r--r--Emby.Server.Implementations/Localization/Core/te.json10
-rw-r--r--Emby.Server.Implementations/Localization/Core/th.json9
-rw-r--r--Emby.Server.Implementations/Localization/LocalizationManager.cs199
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/0-prefer.csv11
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/0-prefer.json34
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/ar.json41
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/au.csv17
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/au.json69
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/be.csv11
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/be.json55
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/bg.json34
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/br.csv14
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/br.json55
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/ca.csv18
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/ca.json90
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/cl.json41
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/co.csv7
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/co.json55
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/cz.json34
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/de.csv17
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/de.json41
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/dk.csv7
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/dk.json48
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/es.csv25
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/es.json90
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/fi.csv10
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/fi.json48
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/fr.csv13
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/fr.json69
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/gb.csv23
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/gb.json97
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/gr.json34
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/hu.json41
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/id.json34
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/ie.csv10
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/ie.json55
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/in.json55
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/it.json34
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/jp.csv11
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/jp.json62
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/kr.json41
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/kz.csv6
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/kz.json41
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/lt.json41
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/mx.csv6
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/mx.json41
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/nl.csv8
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/nl.json55
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/no.csv10
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/no.json69
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/nz.csv16
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/nz.json76
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/ph.json48
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/pl.json41
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/pt.json62
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/ro.csv6
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/ro.json48
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/ru.csv6
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/ru.json48
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/se.csv10
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/se.json55
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/sg.json48
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/sk.csv6
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/sk.json41
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/th.json48
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/tr.json69
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/tw.json41
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/ua.json34
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/uk.csv22
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/uk.json97
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/us.csv52
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/us.json83
-rw-r--r--Emby.Server.Implementations/Localization/Ratings/za.json55
-rw-r--r--Emby.Server.Implementations/Localization/iso6392.txt4
-rw-r--r--Emby.Server.Implementations/MediaEncoder/EncodingManager.cs272
-rw-r--r--Emby.Server.Implementations/Playlists/PlaylistManager.cs18
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs987
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/TaskManager.cs379
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/AudioNormalizationTask.cs15
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs240
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs101
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/CleanupCollectionAndPlaylistPathsTask.cs11
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs203
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs130
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs171
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/MediaSegmentExtractionTask.cs9
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/OptimizeDatabaseTask.cs114
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/PeopleValidationTask.cs94
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs164
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Tasks/RefreshMediaLibraryTask.cs83
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs121
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Triggers/IntervalTrigger.cs155
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Triggers/StartupTrigger.cs69
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/Triggers/WeeklyTrigger.cs161
-rw-r--r--Emby.Server.Implementations/ServerApplicationPaths.cs7
-rw-r--r--Emby.Server.Implementations/Session/SessionManager.cs14
-rw-r--r--Emby.Server.Implementations/Sorting/DateLastMediaAddedComparer.cs6
-rw-r--r--Emby.Server.Implementations/Sorting/DatePlayedComparer.cs8
-rw-r--r--Emby.Server.Implementations/Sorting/IsFavoriteOrLikeComparer.cs6
-rw-r--r--Emby.Server.Implementations/Sorting/IsPlayedComparer.cs6
-rw-r--r--Emby.Server.Implementations/Sorting/IsUnplayedComparer.cs6
-rw-r--r--Emby.Server.Implementations/Sorting/OfficialRatingComparer.cs71
-rw-r--r--Emby.Server.Implementations/Sorting/PlayCountComparer.cs8
-rw-r--r--Emby.Server.Implementations/SyncPlay/Group.cs16
-rw-r--r--Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs36
-rw-r--r--Emby.Server.Implementations/SystemManager.cs36
-rw-r--r--Jellyfin.Api/Controllers/AudioController.cs24
-rw-r--r--Jellyfin.Api/Controllers/BackupController.cs127
-rw-r--r--Jellyfin.Api/Controllers/BrandingController.cs13
-rw-r--r--Jellyfin.Api/Controllers/ConfigurationController.cs25
-rw-r--r--Jellyfin.Api/Controllers/DynamicHlsController.cs90
-rw-r--r--Jellyfin.Api/Controllers/ImageController.cs3
-rw-r--r--Jellyfin.Api/Controllers/ItemUpdateController.cs8
-rw-r--r--Jellyfin.Api/Controllers/ItemsController.cs4
-rw-r--r--Jellyfin.Api/Controllers/LiveTvController.cs4
-rw-r--r--Jellyfin.Api/Controllers/LocalizationController.cs5
-rw-r--r--Jellyfin.Api/Controllers/MediaSegmentsController.cs5
-rw-r--r--Jellyfin.Api/Controllers/PlaylistsController.cs39
-rw-r--r--Jellyfin.Api/Controllers/PlaystateController.cs3
-rw-r--r--Jellyfin.Api/Controllers/StartupController.cs5
-rw-r--r--Jellyfin.Api/Controllers/SyncPlayController.cs28
-rw-r--r--Jellyfin.Api/Controllers/SystemController.cs15
-rw-r--r--Jellyfin.Api/Controllers/UniversalAudioController.cs4
-rw-r--r--Jellyfin.Api/Controllers/VideosController.cs24
-rw-r--r--Jellyfin.Api/Controllers/YearsController.cs2
-rw-r--r--Jellyfin.Api/Helpers/DynamicHlsHelper.cs85
-rw-r--r--Jellyfin.Api/Helpers/MediaInfoHelper.cs7
-rw-r--r--Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs20
-rw-r--r--Jellyfin.Api/Middleware/LanFilteringMiddleware.cs51
-rw-r--r--Jellyfin.Api/Models/StartupDtos/StartupConfigurationDto.cs5
-rw-r--r--Jellyfin.Api/Models/SystemInfoDtos/FolderStorageDto.cs46
-rw-r--r--Jellyfin.Api/Models/SystemInfoDtos/LibraryStorageDto.cs37
-rw-r--r--Jellyfin.Api/Models/SystemInfoDtos/SystemStorageDto.cs67
-rw-r--r--Jellyfin.Data/Enums/VideoRangeType.cs21
-rw-r--r--Jellyfin.Server.Implementations/Extensions/ExpressionExtensions.cs70
-rw-r--r--Jellyfin.Server.Implementations/Extensions/ServiceCollectionExtensions.cs59
-rw-r--r--Jellyfin.Server.Implementations/FullSystemBackup/BackupManifest.cs19
-rw-r--r--Jellyfin.Server.Implementations/FullSystemBackup/BackupOptions.cs15
-rw-r--r--Jellyfin.Server.Implementations/FullSystemBackup/BackupService.cs512
-rw-r--r--Jellyfin.Server.Implementations/Item/BaseItemRepository.cs543
-rw-r--r--Jellyfin.Server.Implementations/Item/ChapterRepository.cs37
-rw-r--r--Jellyfin.Server.Implementations/Item/KeyframeRepository.cs72
-rw-r--r--Jellyfin.Server.Implementations/Item/MediaStreamRepository.cs17
-rw-r--r--Jellyfin.Server.Implementations/Item/OrderMapper.cs2
-rw-r--r--Jellyfin.Server.Implementations/Item/PeopleRepository.cs60
-rw-r--r--Jellyfin.Server.Implementations/MediaSegments/MediaSegmentManager.cs31
-rw-r--r--Jellyfin.Server.Implementations/StorageHelpers/StorageHelper.cs111
-rw-r--r--Jellyfin.Server.Implementations/Trickplay/TrickplayManager.cs169
-rw-r--r--Jellyfin.Server.Implementations/Users/UserManager.cs6
-rw-r--r--Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs10
-rw-r--r--Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs6
-rw-r--r--Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs116
-rw-r--r--Jellyfin.Server/Filters/AdditionalModelFilter.cs107
-rw-r--r--Jellyfin.Server/Helpers/StartupHelpers.cs6
-rw-r--r--Jellyfin.Server/Jellyfin.Server.csproj4
-rw-r--r--Jellyfin.Server/Migrations/IAsyncMigrationRoutine.cs31
-rw-r--r--Jellyfin.Server/Migrations/IDatabaseMigrationRoutine.cs2
-rw-r--r--Jellyfin.Server/Migrations/IMigrationRoutine.cs32
-rw-r--r--Jellyfin.Server/Migrations/JellyfinMigrationAttribute.cs68
-rw-r--r--Jellyfin.Server/Migrations/JellyfinMigrationBackupAttribute.cs35
-rw-r--r--Jellyfin.Server/Migrations/JellyfinMigrationService.cs451
-rw-r--r--Jellyfin.Server/Migrations/MigrationRunner.cs181
-rw-r--r--Jellyfin.Server/Migrations/MigrationsFactory.cs20
-rw-r--r--Jellyfin.Server/Migrations/MigrationsListStore.cs24
-rw-r--r--Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs12
-rw-r--r--Jellyfin.Server/Migrations/PreStartupRoutines/MigrateEncodingOptions.cs12
-rw-r--r--Jellyfin.Server/Migrations/PreStartupRoutines/MigrateMusicBrainzTimeout.cs12
-rw-r--r--Jellyfin.Server/Migrations/PreStartupRoutines/MigrateNetworkConfiguration.cs10
-rw-r--r--Jellyfin.Server/Migrations/PreStartupRoutines/RenameEnableGroupingIntoCollections.cs12
-rw-r--r--Jellyfin.Server/Migrations/Routines/AddDefaultCastReceivers.cs12
-rw-r--r--Jellyfin.Server/Migrations/Routines/AddDefaultPluginRepository.cs12
-rw-r--r--Jellyfin.Server/Migrations/Routines/CreateUserLoggingConfigFile.cs12
-rw-r--r--Jellyfin.Server/Migrations/Routines/DisableTranscodingThrottling.cs12
-rw-r--r--Jellyfin.Server/Migrations/Routines/FixAudioData.cs37
-rw-r--r--Jellyfin.Server/Migrations/Routines/FixPlaylistOwner.cs12
-rw-r--r--Jellyfin.Server/Migrations/Routines/MigrateActivityLogDb.cs12
-rw-r--r--Jellyfin.Server/Migrations/Routines/MigrateAuthenticationDb.cs12
-rw-r--r--Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs12
-rw-r--r--Jellyfin.Server/Migrations/Routines/MigrateKeyframeData.cs152
-rw-r--r--Jellyfin.Server/Migrations/Routines/MigrateLibraryDb.cs590
-rw-r--r--Jellyfin.Server/Migrations/Routines/MigrateLibraryDbCompatibilityCheck.cs73
-rw-r--r--Jellyfin.Server/Migrations/Routines/MigrateRatingLevels.cs133
-rw-r--r--Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs332
-rw-r--r--Jellyfin.Server/Migrations/Routines/MoveExtractedFiles.cs295
-rw-r--r--Jellyfin.Server/Migrations/Routines/MoveTrickplayFiles.cs45
-rw-r--r--Jellyfin.Server/Migrations/Routines/ReaddDefaultPluginRepository.cs65
-rw-r--r--Jellyfin.Server/Migrations/Routines/RefreshInternalDateModified.cs131
-rw-r--r--Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs69
-rw-r--r--Jellyfin.Server/Migrations/Routines/RemoveDuplicateExtras.cs111
-rw-r--r--Jellyfin.Server/Migrations/Routines/RemoveDuplicatePlaylistChildren.cs17
-rw-r--r--Jellyfin.Server/Migrations/Routines/UpdateDefaultPluginRepository.cs12
-rw-r--r--Jellyfin.Server/Migrations/Stages/CodeMigration.cs81
-rw-r--r--Jellyfin.Server/Migrations/Stages/JellyfinMigrationStageTypes.cs26
-rw-r--r--Jellyfin.Server/Migrations/Stages/MigrationStage.cs16
-rw-r--r--Jellyfin.Server/Program.cs114
-rw-r--r--Jellyfin.Server/ServerSetupApp/IStartupLogger.cs25
-rw-r--r--Jellyfin.Server/ServerSetupApp/SetupServer.cs246
-rw-r--r--Jellyfin.Server/ServerSetupApp/StartupLogger.cs102
-rw-r--r--Jellyfin.Server/ServerSetupApp/index.mstemplate.html225
-rw-r--r--Jellyfin.Server/Startup.cs12
-rw-r--r--Jellyfin.Server/StartupOptions.cs6
-rw-r--r--MediaBrowser.Common/Configuration/EncodingConfigurationExtensions.cs3
-rw-r--r--MediaBrowser.Common/Configuration/IApplicationPaths.cs19
-rw-r--r--MediaBrowser.Common/Extensions/HttpContextExtensions.cs2
-rw-r--r--MediaBrowser.Common/Net/INetworkManager.cs4
-rw-r--r--MediaBrowser.Common/Net/NetworkUtils.cs21
-rw-r--r--MediaBrowser.Common/Net/RemoteAccessPolicyResult.cs29
-rw-r--r--MediaBrowser.Common/Plugins/BasePluginOfT.cs5
-rw-r--r--MediaBrowser.Controller/Chapters/IChapterManager.cs55
-rw-r--r--MediaBrowser.Controller/Dto/DtoOptions.cs2
-rw-r--r--MediaBrowser.Controller/Entities/BaseItem.cs125
-rw-r--r--MediaBrowser.Controller/Entities/Folder.cs17
-rw-r--r--MediaBrowser.Controller/Entities/InternalItemsQuery.cs21
-rw-r--r--MediaBrowser.Controller/Entities/Movies/BoxSet.cs2
-rw-r--r--MediaBrowser.Controller/Entities/TV/Episode.cs39
-rw-r--r--MediaBrowser.Controller/Entities/TV/Series.cs6
-rw-r--r--MediaBrowser.Controller/Entities/UserViewBuilder.cs5
-rw-r--r--MediaBrowser.Controller/IO/IExternalDataManager.cs19
-rw-r--r--MediaBrowser.Controller/IO/IPathManager.cs56
-rw-r--r--MediaBrowser.Controller/IServerApplicationHost.cs5
-rw-r--r--MediaBrowser.Controller/IServerApplicationPaths.cs4
-rw-r--r--MediaBrowser.Controller/ISystemManager.cs7
-rw-r--r--MediaBrowser.Controller/Library/IKeyframeManager.cs37
-rw-r--r--MediaBrowser.Controller/Library/ILibraryManager.cs8
-rw-r--r--MediaBrowser.Controller/MediaBrowser.Controller.csproj1
-rw-r--r--MediaBrowser.Controller/MediaEncoding/BitStreamFilterOptionType.cs32
-rw-r--r--MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs334
-rw-r--r--MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs1
-rw-r--r--MediaBrowser.Controller/MediaEncoding/FilterOptionType.cs12
-rw-r--r--MediaBrowser.Controller/MediaEncoding/IAttachmentExtractor.cs47
-rw-r--r--MediaBrowser.Controller/MediaEncoding/IEncodingManager.cs28
-rw-r--r--MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs13
-rw-r--r--MediaBrowser.Controller/MediaSegments/IMediaSegmentManager.cs22
-rw-r--r--MediaBrowser.Controller/MediaSegments/IMediaSegmentProvider.cs6
-rw-r--r--MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandMessage.cs24
-rw-r--r--MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfGroupInfoMessage.cs25
-rw-r--r--MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfGroupStateUpdateMessage.cs25
-rw-r--r--MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfPlayQueueUpdateMessage.cs25
-rw-r--r--MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfStringMessage.cs25
-rw-r--r--MediaBrowser.Controller/Persistence/IChapterRepository.cs (renamed from MediaBrowser.Controller/Chapters/IChapterRepository.cs)26
-rw-r--r--MediaBrowser.Controller/Persistence/IKeyframeRepository.cs37
-rw-r--r--MediaBrowser.Controller/Session/ISessionManager.cs2
-rw-r--r--MediaBrowser.Controller/Sorting/IUserBaseItemComparer.cs2
-rw-r--r--MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs12
-rw-r--r--MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs16
-rw-r--r--MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs11
-rw-r--r--MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs11
-rw-r--r--MediaBrowser.Controller/SystemBackupService/BackupManifestDto.cs34
-rw-r--r--MediaBrowser.Controller/SystemBackupService/BackupOptionsDto.cs29
-rw-r--r--MediaBrowser.Controller/SystemBackupService/BackupRestoreRequestDto.cs15
-rw-r--r--MediaBrowser.Controller/SystemBackupService/IBackupService.cs48
-rw-r--r--MediaBrowser.Controller/Trickplay/ITrickplayManager.cs12
-rw-r--r--MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs3
-rw-r--r--MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs416
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/ApplePlatformHelper.cs87
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs118
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs69
-rw-r--r--MediaBrowser.MediaEncoding/Probing/InternalMediaInfoResult.cs7
-rw-r--r--MediaBrowser.MediaEncoding/Probing/MediaFrameInfo.cs184
-rw-r--r--MediaBrowser.MediaEncoding/Probing/MediaFrameSideDataInfo.cs16
-rw-r--r--MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs17
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs33
-rw-r--r--MediaBrowser.MediaEncoding/Transcoding/TranscodeManager.cs11
-rw-r--r--MediaBrowser.Model/Branding/BrandingOptions.cs7
-rw-r--r--MediaBrowser.Model/Branding/BrandingOptionsDto.cs25
-rw-r--r--MediaBrowser.Model/Dlna/ConditionProcessor.cs9
-rw-r--r--MediaBrowser.Model/Dlna/StreamBuilder.cs32
-rw-r--r--MediaBrowser.Model/Dlna/StreamInfo.cs21
-rw-r--r--MediaBrowser.Model/Dto/BaseItemDto.cs4
-rw-r--r--MediaBrowser.Model/Dto/BaseItemPerson.cs2
-rw-r--r--MediaBrowser.Model/Dto/MediaSourceInfo.cs4
-rw-r--r--MediaBrowser.Model/Dto/MetadataEditorInfo.cs70
-rw-r--r--MediaBrowser.Model/Entities/MediaAttachment.cs80
-rw-r--r--MediaBrowser.Model/Entities/MediaStream.cs43
-rw-r--r--MediaBrowser.Model/Entities/ParentalRating.cs55
-rw-r--r--MediaBrowser.Model/Entities/ParentalRatingEntry.cs22
-rw-r--r--MediaBrowser.Model/Entities/ParentalRatingScore.cs32
-rw-r--r--MediaBrowser.Model/Entities/ParentalRatingSystem.cs28
-rw-r--r--MediaBrowser.Model/Extensions/ContainerHelper.cs4
-rw-r--r--MediaBrowser.Model/Extensions/EnumerableExtensions.cs2
-rw-r--r--MediaBrowser.Model/Globalization/ILocalizationManager.cs110
-rw-r--r--MediaBrowser.Model/IO/AsyncFile.cs8
-rw-r--r--MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs2
-rw-r--r--MediaBrowser.Model/LiveTv/TunerHostInfo.cs3
-rw-r--r--MediaBrowser.Model/Lyrics/LyricLine.cs11
-rw-r--r--MediaBrowser.Model/Lyrics/LyricLineCue.cs35
-rw-r--r--MediaBrowser.Model/Lyrics/LyricSearchRequest.cs7
-rw-r--r--MediaBrowser.Model/MediaInfo/AudioIndexSource.cs30
-rw-r--r--MediaBrowser.Model/MediaSegments/MediaSegmentDto.cs2
-rw-r--r--MediaBrowser.Model/Querying/ItemFields.cs79
-rw-r--r--MediaBrowser.Model/Search/SearchHint.cs2
-rw-r--r--MediaBrowser.Model/SyncPlay/GroupUpdate.cs17
-rw-r--r--MediaBrowser.Model/SyncPlay/GroupUpdateOfT.cs31
-rw-r--r--MediaBrowser.Model/SyncPlay/GroupUpdateType.cs10
-rw-r--r--MediaBrowser.Model/SyncPlay/SyncPlayGroupDoesNotExistUpdate.cs21
-rw-r--r--MediaBrowser.Model/SyncPlay/SyncPlayGroupJoinedUpdate.cs21
-rw-r--r--MediaBrowser.Model/SyncPlay/SyncPlayGroupLeftUpdate.cs21
-rw-r--r--MediaBrowser.Model/SyncPlay/SyncPlayLibraryAccessDeniedUpdate.cs21
-rw-r--r--MediaBrowser.Model/SyncPlay/SyncPlayNotInGroupUpdate.cs21
-rw-r--r--MediaBrowser.Model/SyncPlay/SyncPlayPlayQueueUpdate.cs21
-rw-r--r--MediaBrowser.Model/SyncPlay/SyncPlayStateUpdate.cs21
-rw-r--r--MediaBrowser.Model/SyncPlay/SyncPlayUserJoinedUpdate.cs21
-rw-r--r--MediaBrowser.Model/SyncPlay/SyncPlayUserLeftUpdate.cs21
-rw-r--r--MediaBrowser.Model/System/FolderStorageInfo.cs32
-rw-r--r--MediaBrowser.Model/System/LibraryStorageInfo.cs25
-rw-r--r--MediaBrowser.Model/System/SystemInfo.cs254
-rw-r--r--MediaBrowser.Model/System/SystemStorageInfo.cs56
-rw-r--r--MediaBrowser.Model/Users/UserPolicy.cs2
-rw-r--r--MediaBrowser.Providers/Books/AudioBookMetadataService.cs75
-rw-r--r--MediaBrowser.Providers/Books/BookMetadataService.cs53
-rw-r--r--MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs119
-rw-r--r--MediaBrowser.Providers/Channels/ChannelMetadataService.cs37
-rw-r--r--MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs37
-rw-r--r--MediaBrowser.Providers/Folders/FolderMetadataService.cs45
-rw-r--r--MediaBrowser.Providers/Folders/UserViewMetadataService.cs37
-rw-r--r--MediaBrowser.Providers/Genres/GenreMetadataService.cs37
-rw-r--r--MediaBrowser.Providers/LiveTv/LiveTvMetadataService.cs37
-rw-r--r--MediaBrowser.Providers/Lyric/LrcLyricParser.cs45
-rw-r--r--MediaBrowser.Providers/Lyric/LyricManager.cs3
-rw-r--r--MediaBrowser.Providers/Lyric/LyricScheduledTask.cs3
-rw-r--r--MediaBrowser.Providers/Manager/ImageSaver.cs16
-rw-r--r--MediaBrowser.Providers/Manager/MetadataService.cs62
-rw-r--r--MediaBrowser.Providers/Manager/ProviderManager.cs3
-rw-r--r--MediaBrowser.Providers/MediaInfo/AudioFileProber.cs93
-rw-r--r--MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs47
-rw-r--r--MediaBrowser.Providers/MediaInfo/ProbeProvider.cs17
-rw-r--r--MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs1
-rw-r--r--MediaBrowser.Providers/Movies/MovieMetadataService.cs57
-rw-r--r--MediaBrowser.Providers/Movies/TrailerMetadataService.cs59
-rw-r--r--MediaBrowser.Providers/Music/AlbumMetadataService.cs354
-rw-r--r--MediaBrowser.Providers/Music/ArtistMetadataService.cs64
-rw-r--r--MediaBrowser.Providers/Music/AudioMetadataService.cs106
-rw-r--r--MediaBrowser.Providers/Music/MusicVideoMetadataService.cs84
-rw-r--r--MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs37
-rw-r--r--MediaBrowser.Providers/People/PersonMetadataService.cs37
-rw-r--r--MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs37
-rw-r--r--MediaBrowser.Providers/Photos/PhotoMetadataService.cs37
-rw-r--r--MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs2
-rw-r--r--MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs105
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs2
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/TmdbExternalUrlProvider.cs23
-rw-r--r--MediaBrowser.Providers/Studios/StudioMetadataService.cs37
-rw-r--r--MediaBrowser.Providers/TV/EpisodeMetadataService.cs159
-rw-r--r--MediaBrowser.Providers/TV/SeasonMetadataService.cs150
-rw-r--r--MediaBrowser.Providers/TV/SeriesMetadataService.cs414
-rw-r--r--MediaBrowser.Providers/Trickplay/TrickplayImagesTask.cs10
-rw-r--r--MediaBrowser.Providers/Trickplay/TrickplayProvider.cs2
-rw-r--r--MediaBrowser.Providers/Videos/VideoMetadataService.cs45
-rw-r--r--MediaBrowser.Providers/Years/YearMetadataService.cs37
-rw-r--r--MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs2
-rw-r--r--MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs4
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/DbConfiguration/CustomDatabaseOption.cs19
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/DbConfiguration/CustomDatabaseOptions.cs32
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/DbConfiguration/DatabaseConfigurationOptions.cs13
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/DbConfiguration/DatabaseLockingBehaviorTypes.cs22
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/AttachmentStreamInfo.cs2
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/BaseItemEntity.cs4
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/KeyframeData.cs32
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/MediaStreamInfo.cs2
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/TrickplayInfo.cs1
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/User.cs10
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/IJellyfinDatabaseProvider.cs20
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/Jellyfin.Database.Implementations.csproj14
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/JellyfinDbContext.cs60
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/JellyfinQueryHelperExtensions.cs166
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/Locking/IEntityFrameworkCoreLockingBehavior.cs32
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/Locking/NoLockBehavior.cs41
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/Locking/OptimisticLockBehavior.cs137
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/Locking/PessimisticLockBehavior.cs296
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/AncestorIdConfiguration.cs4
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/BaseItemConfiguration.cs2
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/ItemValuesConfiguration.cs3
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/KeyframeDataConfiguration.cs18
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/ProgressablePartitionReporting.cs55
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Implementations/QueryPartitionHelpers.cs215
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250326065026_AddInheritedParentalRatingSubValue.Designer.cs1658
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250326065026_AddInheritedParentalRatingSubValue.cs48
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250327101120_AddKeyframeData.Designer.cs1681
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250327101120_AddKeyframeData.cs41
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250327171413_AddHdr10PlusFlag.Designer.cs1655
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250327171413_AddHdr10PlusFlag.cs28
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250331182844_FixAttachmentMigration.Designer.cs1657
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250331182844_FixAttachmentMigration.cs36
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250401142247_FixAncestors.Designer.cs1658
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250401142247_FixAncestors.cs20
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250405075612_FixItemValuesIndices.Designer.cs1694
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250405075612_FixItemValuesIndices.cs47
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/JellyfinDbModelSnapshot.cs265
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/SqliteDesignTimeJellyfinDbFactory.cs4
-rw-r--r--src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/SqliteDatabaseProvider.cs66
-rw-r--r--src/Jellyfin.Drawing.Skia/SkiaEncoder.cs55
-rw-r--r--src/Jellyfin.Drawing.Skia/SkiaExtensions.cs58
-rw-r--r--src/Jellyfin.Drawing.Skia/SplashscreenBuilder.cs8
-rw-r--r--src/Jellyfin.Drawing.Skia/StripCollageBuilder.cs83
-rw-r--r--src/Jellyfin.Drawing.Skia/UnplayedCountIndicator.cs8
-rw-r--r--src/Jellyfin.Drawing/ImageProcessor.cs6
-rw-r--r--src/Jellyfin.Extensions/FileHelper.cs20
-rw-r--r--src/Jellyfin.Extensions/StringExtensions.cs13
-rw-r--r--src/Jellyfin.LiveTv/Channels/ChannelManager.cs9
-rw-r--r--src/Jellyfin.LiveTv/LiveTvDtoService.cs4
-rw-r--r--src/Jellyfin.LiveTv/LiveTvManager.cs34
-rw-r--r--src/Jellyfin.LiveTv/Recordings/RecordingsManager.cs2
-rw-r--r--src/Jellyfin.LiveTv/TunerHosts/M3UTunerHost.cs2
-rw-r--r--src/Jellyfin.MediaEncoding.Hls/Cache/CacheDecorator.cs79
-rw-r--r--src/Jellyfin.MediaEncoding.Hls/Extractors/FfProbeKeyframeExtractor.cs2
-rw-r--r--src/Jellyfin.MediaEncoding.Hls/Extractors/IKeyframeExtractor.cs4
-rw-r--r--src/Jellyfin.MediaEncoding.Hls/Extractors/MatroskaKeyframeExtractor.cs2
-rw-r--r--src/Jellyfin.MediaEncoding.Hls/Jellyfin.MediaEncoding.Hls.csproj1
-rw-r--r--src/Jellyfin.MediaEncoding.Hls/Playlist/CreateMainPlaylistRequest.cs11
-rw-r--r--src/Jellyfin.MediaEncoding.Hls/Playlist/DynamicHlsPlaylistGenerator.cs8
-rw-r--r--src/Jellyfin.MediaEncoding.Hls/ScheduledTasks/KeyframeExtractionScheduledTask.cs24
-rw-r--r--src/Jellyfin.MediaEncoding.Keyframes/Jellyfin.MediaEncoding.Keyframes.csproj13
-rw-r--r--src/Jellyfin.Networking/Manager/NetworkManager.cs312
-rw-r--r--tests/Jellyfin.Api.Tests/Controllers/SystemControllerTests.cs1
-rw-r--r--tests/Jellyfin.Api.Tests/Controllers/UserControllerTests.cs4
-rw-r--r--tests/Jellyfin.Extensions.Tests/FileHelperTests.cs23
-rw-r--r--tests/Jellyfin.LiveTv.Tests/Listings/XmlTvListingsProviderTests.cs4
-rw-r--r--tests/Jellyfin.LiveTv.Tests/Test Data/LiveTv/Listings/XmlTv/emptycategory.xml2
-rw-r--r--tests/Jellyfin.LiveTv.Tests/Test Data/LiveTv/Listings/XmlTv/notitle.xml2
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs34
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/video_single_frame_mjpeg.json209
-rw-r--r--tests/Jellyfin.Model.Tests/Dlna/LegacyStreamInfo.cs21
-rw-r--r--tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs8
-rw-r--r--tests/Jellyfin.Model.Tests/Dlna/StreamInfoTests.cs4
-rw-r--r--tests/Jellyfin.Model.Tests/Test Data/DeviceProfile-Tizen3-stereo.json16
-rw-r--r--tests/Jellyfin.Model.Tests/Test Data/DeviceProfile-Tizen4-4K-5.1.json16
-rw-r--r--tests/Jellyfin.Networking.Tests/NetworkParseTests.cs48
-rw-r--r--tests/Jellyfin.Providers.Tests/Lyrics/LrcLyricParserTests.cs41
-rw-r--r--tests/Jellyfin.Providers.Tests/Manager/ProviderManagerTests.cs1
-rw-r--r--tests/Jellyfin.Providers.Tests/Test Data/Lyrics/Fleetwood Mac - Rumors.elrc31
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs184
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Library/DotIgnoreIgnoreRuleTest.cs30
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs91
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Playlists/PlaylistManagerTests.cs40
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs5
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs8
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs44
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/OpenApiSpecTests.cs3
496 files changed, 27747 insertions, 7868 deletions
diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json
index bc2098a53..f41dcff2a 100644
--- a/.config/dotnet-tools.json
+++ b/.config/dotnet-tools.json
@@ -3,7 +3,7 @@
"isRoot": true,
"tools": {
"dotnet-ef": {
- "version": "9.0.3",
+ "version": "9.0.5",
"commands": [
"dotnet-ef"
]
diff --git a/.github/ISSUE_TEMPLATE/issue report.yml b/.github/ISSUE_TEMPLATE/issue report.yml
index 4f58c5bc5..269968839 100644
--- a/.github/ISSUE_TEMPLATE/issue report.yml
+++ b/.github/ISSUE_TEMPLATE/issue report.yml
@@ -1,6 +1,7 @@
name: Issue Report
description: File an issue report
labels: [bug, triage]
+type: Bug
body:
- type: markdown
id: introduction
@@ -140,7 +141,9 @@ body:
- **Reverse Proxy**: [e.g. none, nginx, apache, etc.]
- **Base URL**: [e.g. none, yes: /example]
- **Networking**: [e.g. Host, Bridge/NAT]
- - **Storage**: [e.g. local, NFS, cloud]
+ - **Jellyfin Data Storage**: [e.g. local SATA SSD, local HDD]
+ - **Media Storage**: [e.g. Local HDD, SMB Share]
+ - **External Integrations**: [e.g. Jellystat, Jellyseerr]
value: |
- OS:
- Linux Kernel:
@@ -155,7 +158,9 @@ body:
- Reverse Proxy:
- Base URL:
- Networking:
- - Storage:
+ - Jellyfin Data Storage:
+ - Media Storage:
+ - External Integrations:
render: markdown
validations:
required: true
diff --git a/.github/workflows/ci-codeql-analysis.yml b/.github/workflows/ci-codeql-analysis.yml
index 9faab47db..334a2edcf 100644
--- a/.github/workflows/ci-codeql-analysis.yml
+++ b/.github/workflows/ci-codeql-analysis.yml
@@ -27,11 +27,11 @@ jobs:
dotnet-version: '9.0.x'
- name: Initialize CodeQL
- uses: github/codeql-action/init@1b549b9259bda1cb5ddde3b41741a82a2d15a841 # v3.28.13
+ uses: github/codeql-action/init@fca7ace96b7d713c7035871441bd52efbe39e27e # v3.28.19
with:
languages: ${{ matrix.language }}
queries: +security-extended
- name: Autobuild
- uses: github/codeql-action/autobuild@1b549b9259bda1cb5ddde3b41741a82a2d15a841 # v3.28.13
+ uses: github/codeql-action/autobuild@fca7ace96b7d713c7035871441bd52efbe39e27e # v3.28.19
- name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@1b549b9259bda1cb5ddde3b41741a82a2d15a841 # v3.28.13
+ uses: github/codeql-action/analyze@fca7ace96b7d713c7035871441bd52efbe39e27e # v3.28.19
diff --git a/.github/workflows/ci-compat.yml b/.github/workflows/ci-compat.yml
index 13b029e52..7dfcd9477 100644
--- a/.github/workflows/ci-compat.yml
+++ b/.github/workflows/ci-compat.yml
@@ -85,13 +85,13 @@ jobs:
steps:
- name: Download abi-head
- uses: actions/download-artifact@95815c38cf2ff2164869cbab79da8d1f422bc89e # v4.2.1
+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: abi-head
path: abi-head
- name: Download abi-base
- uses: actions/download-artifact@95815c38cf2ff2164869cbab79da8d1f422bc89e # v4.2.1
+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: abi-base
path: abi-base
@@ -105,7 +105,7 @@ jobs:
run: |
{
echo 'body<<EOF'
- for file in Jellyfin.Data.dll MediaBrowser.Common.dll MediaBrowser.Controller.dll MediaBrowser.Model.dll Emby.Naming.dll Jellyfin.Extensions.dll; do
+ for file in Jellyfin.Data.dll MediaBrowser.Common.dll MediaBrowser.Controller.dll MediaBrowser.Model.dll Emby.Naming.dll Jellyfin.Extensions.dll Jellyfin.MediaEncoding.Keyframes.dll Jellyfin.Database.Implementations.dll; do
COMPAT_OUTPUT="$( { apicompat --left ./abi-base/${file} --right ./abi-head/${file}; } 2>&1 )"
if [ "APICompat ran successfully without finding any breaking changes." != "${COMPAT_OUTPUT}" ]; then
printf "\n${file}\n${COMPAT_OUTPUT}\n"
diff --git a/.github/workflows/ci-openapi.yml b/.github/workflows/ci-openapi.yml
index 95e090f9b..966d86ed2 100644
--- a/.github/workflows/ci-openapi.yml
+++ b/.github/workflows/ci-openapi.yml
@@ -80,12 +80,12 @@ jobs:
- openapi-base
steps:
- name: Download openapi-head
- uses: actions/download-artifact@95815c38cf2ff2164869cbab79da8d1f422bc89e # v4.2.1
+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: openapi-head
path: openapi-head
- name: Download openapi-base
- uses: actions/download-artifact@95815c38cf2ff2164869cbab79da8d1f422bc89e # v4.2.1
+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: openapi-base
path: openapi-base
@@ -158,12 +158,12 @@ jobs:
run: |-
echo "JELLYFIN_VERSION=$(date +'%Y%m%d%H%M%S')" >> $GITHUB_ENV
- name: Download openapi-head
- uses: actions/download-artifact@95815c38cf2ff2164869cbab79da8d1f422bc89e # v4.2.1
+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: openapi-head
path: openapi-head
- name: Upload openapi.json (unstable) to repository server
- uses: appleboy/scp-action@917f8b81dfc1ccd331fef9e2d61bdc6c8be94634 # v0.1.7
+ uses: appleboy/scp-action@ff85246acaad7bdce478db94a363cd2bf7c90345 # v1.0.0
with:
host: "${{ secrets.REPO_HOST }}"
username: "${{ secrets.REPO_USER }}"
@@ -220,12 +220,12 @@ jobs:
run: |-
echo "JELLYFIN_VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_ENV
- name: Download openapi-head
- uses: actions/download-artifact@95815c38cf2ff2164869cbab79da8d1f422bc89e # v4.2.1
+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: openapi-head
path: openapi-head
- name: Upload openapi.json (stable) to repository server
- uses: appleboy/scp-action@917f8b81dfc1ccd331fef9e2d61bdc6c8be94634 # v0.1.7
+ uses: appleboy/scp-action@ff85246acaad7bdce478db94a363cd2bf7c90345 # v1.0.0
with:
host: "${{ secrets.REPO_HOST }}"
username: "${{ secrets.REPO_USER }}"
diff --git a/.github/workflows/ci-tests.yml b/.github/workflows/ci-tests.yml
index be4192a44..048a1c3df 100644
--- a/.github/workflows/ci-tests.yml
+++ b/.github/workflows/ci-tests.yml
@@ -35,7 +35,7 @@ jobs:
--verbosity minimal
- name: Merge code coverage results
- uses: danielpalme/ReportGenerator-GitHub-Action@25b1e0261a9f68d7874dbbace168300558ef68f7 # v5.4.5
+ uses: danielpalme/ReportGenerator-GitHub-Action@c9576654e2fea2faa7b69e59550b3805bf6a9977 # v5.4.7
with:
reports: "**/coverage.cobertura.xml"
targetdir: "merged/"
diff --git a/.github/workflows/commands.yml b/.github/workflows/commands.yml
index 5ec4d164a..374554ac0 100644
--- a/.github/workflows/commands.yml
+++ b/.github/workflows/commands.yml
@@ -44,7 +44,7 @@ jobs:
with:
repository: jellyfin/jellyfin-triage-script
- name: install python
- uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+ uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
with:
python-version: '3.13'
cache: 'pip'
diff --git a/.github/workflows/issue-template-check.yml b/.github/workflows/issue-template-check.yml
index 8a21ab015..588f0a50e 100644
--- a/.github/workflows/issue-template-check.yml
+++ b/.github/workflows/issue-template-check.yml
@@ -14,7 +14,7 @@ jobs:
with:
repository: jellyfin/jellyfin-triage-script
- name: install python
- uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+ uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
with:
python-version: '3.13'
cache: 'pip'
diff --git a/.github/workflows/pull-request-conflict.yml b/.github/workflows/pull-request-conflict.yml
index 411ebf829..e6a9bf0ca 100644
--- a/.github/workflows/pull-request-conflict.yml
+++ b/.github/workflows/pull-request-conflict.yml
@@ -12,7 +12,7 @@ jobs:
label:
name: Labeling
runs-on: ubuntu-latest
- if: ${{ github.repository == 'jellyfin/jellyfin' }}
+ if: ${{ github.repository == 'jellyfin/jellyfin' && github.event.issue.pull_request }}
steps:
- name: Apply label
uses: eps1lon/actions-label-merge-conflict@1df065ebe6e3310545d4f4c4e862e43bdca146f0 # v3.0.3
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index 0dcce1ea1..1ff5607ea 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -195,6 +195,7 @@
- [Kenneth Cochran](https://github.com/kennethcochran)
- [benedikt257](https://github.com/benedikt257)
- [revam](https://github.com/revam)
+ - [allesmi](https://github.com/allesmi)
# Emby Contributors
@@ -270,3 +271,4 @@
- [Nathan McCrina](https://github.com/nfmccrina)
- [Martin Reuter](https://github.com/reuterma24)
- [Michael McElroy](https://github.com/mcmcelro)
+ - [Soumyadip Auddy](https://github.com/SoumyadipAuddy)
diff --git a/Directory.Packages.props b/Directory.Packages.props
index f9e111b38..a0a09d745 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -4,52 +4,54 @@
</PropertyGroup>
<!-- Run "dotnet list package (dash,dash)outdated" to see the latest versions of each package.-->
<ItemGroup Label="Package Dependencies">
- <PackageVersion Include="AsyncKeyedLock" Version="7.1.4" />
+ <PackageVersion Include="AsyncKeyedLock" Version="7.1.6" />
<PackageVersion Include="AutoFixture.AutoMoq" Version="4.18.1" />
<PackageVersion Include="AutoFixture.Xunit2" Version="4.18.1" />
<PackageVersion Include="AutoFixture" Version="4.18.1" />
<PackageVersion Include="BDInfo" Version="0.8.0" />
<PackageVersion Include="BitFaster.Caching" Version="2.5.3" />
- <PackageVersion Include="BlurHashSharp.SkiaSharp" Version="1.3.4" />
- <PackageVersion Include="BlurHashSharp" Version="1.3.4" />
+ <PackageVersion Include="BlurHashSharp.SkiaSharp" Version="1.4.0-pre.1" />
+ <PackageVersion Include="BlurHashSharp" Version="1.4.0-pre.1" />
<PackageVersion Include="CommandLineParser" Version="2.9.1" />
<PackageVersion Include="coverlet.collector" Version="6.0.4" />
<PackageVersion Include="Diacritics" Version="3.3.29" />
<PackageVersion Include="DiscUtils.Udf" Version="0.16.13" />
<PackageVersion Include="DotNet.Glob" Version="3.1.3" />
- <PackageVersion Include="FsCheck.Xunit" Version="3.1.0" />
- <PackageVersion Include="HarfBuzzSharp.NativeAssets.Linux" Version="7.3.0.3" />
+ <PackageVersion Include="FsCheck.Xunit" Version="3.3.0" />
+ <PackageVersion Include="HarfBuzzSharp.NativeAssets.Linux" Version="8.3.1.1" />
<PackageVersion Include="ICU4N.Transliterator" Version="60.1.0-alpha.356" />
<PackageVersion Include="IDisposableAnalyzers" Version="4.0.8" />
+ <PackageVersion Include="Ignore" Version="0.2.1" />
<PackageVersion Include="Jellyfin.XmlTv" Version="10.8.0" />
- <PackageVersion Include="libse" Version="4.0.10" />
+ <PackageVersion Include="libse" Version="4.0.12" />
<PackageVersion Include="LrcParser" Version="2025.228.1" />
<PackageVersion Include="MetaBrainz.MusicBrainz" Version="6.1.0" />
- <PackageVersion Include="Microsoft.AspNetCore.Authorization" Version="9.0.3" />
- <PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.3" />
- <PackageVersion Include="Microsoft.CodeAnalysis.BannedApiAnalyzers" Version="3.3.4" />
- <PackageVersion Include="Microsoft.Data.Sqlite" Version="9.0.3" />
- <PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.3" />
- <PackageVersion Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.3" />
- <PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.3" />
- <PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.3" />
- <PackageVersion Include="Microsoft.Extensions.Caching.Abstractions" Version="9.0.3" />
- <PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="9.0.3" />
- <PackageVersion Include="Microsoft.Extensions.Configuration.Abstractions" Version="9.0.3" />
- <PackageVersion Include="Microsoft.Extensions.Configuration.Binder" Version="9.0.3" />
- <PackageVersion Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="9.0.3" />
- <PackageVersion Include="Microsoft.Extensions.Configuration.Json" Version="9.0.3" />
- <PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.3" />
- <PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="9.0.3" />
- <PackageVersion Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="9.0.3" />
- <PackageVersion Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="9.0.3" />
- <PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="9.0.3" />
- <PackageVersion Include="Microsoft.Extensions.Http" Version="9.0.3" />
- <PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.3" />
- <PackageVersion Include="Microsoft.Extensions.Logging" Version="9.0.3" />
- <PackageVersion Include="Microsoft.Extensions.Options" Version="9.0.3" />
- <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.13.0" />
+ <PackageVersion Include="Microsoft.AspNetCore.Authorization" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.CodeAnalysis.BannedApiAnalyzers" Version="4.14.0" />
+ <PackageVersion Include="Microsoft.Data.Sqlite" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.Extensions.Caching.Abstractions" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.Extensions.Configuration.Abstractions" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.Extensions.Configuration.Binder" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.Extensions.Configuration.Json" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.Extensions.Http" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.Extensions.Logging" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.Extensions.Options" Version="9.0.5" />
+ <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageVersion Include="MimeTypes" Version="2.5.2" />
+ <PackageVersion Include="Morestachio" Version="5.0.1.631" />
<PackageVersion Include="Moq" Version="4.18.4" />
<PackageVersion Include="NEbml" Version="0.12.0" />
<PackageVersion Include="Newtonsoft.Json" Version="13.0.3" />
@@ -57,30 +59,31 @@
<PackageVersion Include="prometheus-net.AspNetCore" Version="8.2.1" />
<PackageVersion Include="prometheus-net.DotNetRuntime" Version="4.4.1" />
<PackageVersion Include="prometheus-net" Version="8.2.1" />
+ <PackageVersion Include="Polly" Version="8.5.2" />
<PackageVersion Include="Serilog.AspNetCore" Version="9.0.0" />
<PackageVersion Include="Serilog.Enrichers.Thread" Version="4.0.0" />
<PackageVersion Include="Serilog.Settings.Configuration" Version="9.0.0" />
<PackageVersion Include="Serilog.Sinks.Async" Version="2.1.0" />
<PackageVersion Include="Serilog.Sinks.Console" Version="6.0.0" />
- <PackageVersion Include="Serilog.Sinks.File" Version="6.0.0" />
+ <PackageVersion Include="Serilog.Sinks.File" Version="7.0.0" />
<PackageVersion Include="Serilog.Sinks.Graylog" Version="3.1.1" />
<PackageVersion Include="SerilogAnalyzer" Version="0.15.0" />
<PackageVersion Include="SharpFuzz" Version="2.2.0" />
- <PackageVersion Include="SkiaSharp" Version="2.88.9" />
- <PackageVersion Include="SkiaSharp.HarfBuzz" Version="2.88.9" />
- <PackageVersion Include="SkiaSharp.NativeAssets.Linux" Version="2.88.9" />
+ <PackageVersion Include="SkiaSharp" Version="3.119.0" />
+ <PackageVersion Include="SkiaSharp.HarfBuzz" Version="3.119.0" />
+ <PackageVersion Include="SkiaSharp.NativeAssets.Linux" Version="3.119.0" />
<PackageVersion Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" />
<PackageVersion Include="StyleCop.Analyzers" Version="1.2.0-beta.556" />
- <PackageVersion Include="Svg.Skia" Version="2.0.0.4" />
+ <PackageVersion Include="Svg.Skia" Version="3.0.3" />
<PackageVersion Include="Swashbuckle.AspNetCore.ReDoc" Version="6.5.0" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageVersion Include="System.Globalization" Version="4.3.0" />
<PackageVersion Include="System.Linq.Async" Version="6.0.1" />
- <PackageVersion Include="System.Text.Encoding.CodePages" Version="9.0.3" />
- <PackageVersion Include="System.Text.Json" Version="9.0.3" />
- <PackageVersion Include="System.Threading.Tasks.Dataflow" Version="9.0.3" />
+ <PackageVersion Include="System.Text.Encoding.CodePages" Version="9.0.5" />
+ <PackageVersion Include="System.Text.Json" Version="9.0.5" />
+ <PackageVersion Include="System.Threading.Tasks.Dataflow" Version="9.0.5" />
<PackageVersion Include="TagLibSharp" Version="2.3.0" />
- <PackageVersion Include="z440.atl.core" Version="6.19.0" />
+ <PackageVersion Include="z440.atl.core" Version="6.24.0" />
<PackageVersion Include="TMDbLib" Version="2.2.0" />
<PackageVersion Include="UTF.Unknown" Version="2.5.1" />
<PackageVersion Include="Xunit.Priority" Version="1.1.6" />
diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs
index 6a662aaf5..dbb848603 100644
--- a/Emby.Naming/Common/NamingOptions.cs
+++ b/Emby.Naming/Common/NamingOptions.cs
@@ -187,7 +187,8 @@ namespace Emby.Naming.Common
"disc",
"disk",
"vol",
- "volume"
+ "volume",
+ "part"
};
ArtistSubfolders = new[]
diff --git a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs
index f0cca9efd..e74755ec3 100644
--- a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs
+++ b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs
@@ -1,5 +1,8 @@
using System;
+using System.Collections.Generic;
using System.IO;
+using System.Linq;
+using Jellyfin.Extensions;
using MediaBrowser.Common.Configuration;
namespace Emby.Server.Implementations.AppBase
@@ -30,7 +33,6 @@ namespace Emby.Server.Implementations.AppBase
ConfigurationDirectoryPath = configurationDirectoryPath;
CachePath = cacheDirectoryPath;
WebPath = webDirectoryPath;
-
DataPath = Directory.CreateDirectory(Path.Combine(ProgramDataPath, "data")).FullName;
}
@@ -75,5 +77,47 @@ namespace Emby.Server.Implementations.AppBase
/// <inheritdoc />
public string TrickplayPath => Path.Combine(DataPath, "trickplay");
+
+ /// <inheritdoc />
+ public string BackupPath => Path.Combine(DataPath, "backups");
+
+ /// <inheritdoc />
+ public virtual void MakeSanityCheckOrThrow()
+ {
+ CreateAndCheckMarker(ConfigurationDirectoryPath, "config");
+ CreateAndCheckMarker(LogDirectoryPath, "log");
+ CreateAndCheckMarker(PluginsPath, "plugin");
+ CreateAndCheckMarker(ProgramDataPath, "data");
+ CreateAndCheckMarker(CachePath, "cache");
+ CreateAndCheckMarker(DataPath, "data");
+ }
+
+ /// <inheritdoc />
+ public void CreateAndCheckMarker(string path, string markerName, bool recursive = false)
+ {
+ Directory.CreateDirectory(path);
+
+ CheckOrCreateMarker(path, $".jellyfin-{markerName}", recursive);
+ }
+
+ private IEnumerable<string> GetMarkers(string path, bool recursive = false)
+ {
+ return Directory.EnumerateFiles(path, ".jellyfin-*", recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
+ }
+
+ private void CheckOrCreateMarker(string path, string markerName, bool recursive = false)
+ {
+ var otherMarkers = GetMarkers(path, recursive).FirstOrDefault(e => Path.GetFileName(e) != markerName);
+ if (otherMarkers != null)
+ {
+ throw new InvalidOperationException($"Exepected to find only {markerName} but found marker for {otherMarkers}.");
+ }
+
+ var markerPath = Path.Combine(path, markerName);
+ if (!File.Exists(markerPath))
+ {
+ FileHelper.CreateEmpty(markerPath);
+ }
+ }
}
}
diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs
index 9bc3a0204..81ef0e5f9 100644
--- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs
+++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs
@@ -227,6 +227,7 @@ namespace Emby.Server.Implementations.AppBase
Logger.LogInformation("Setting cache path: {Path}", cachePath);
((BaseApplicationPaths)CommonApplicationPaths).CachePath = cachePath;
+ CommonApplicationPaths.CreateAndCheckMarker(((BaseApplicationPaths)CommonApplicationPaths).CachePath, "cache");
}
/// <summary>
diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs
index 4d959905d..565d0f0c8 100644
--- a/Emby.Server.Implementations/ApplicationHost.cs
+++ b/Emby.Server.Implementations/ApplicationHost.cs
@@ -15,6 +15,7 @@ using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Emby.Naming.Common;
using Emby.Photos;
+using Emby.Server.Implementations.Chapters;
using Emby.Server.Implementations.Collections;
using Emby.Server.Implementations.Configuration;
using Emby.Server.Implementations.Cryptography;
@@ -35,13 +36,14 @@ using Emby.Server.Implementations.SyncPlay;
using Emby.Server.Implementations.TV;
using Emby.Server.Implementations.Updates;
using Jellyfin.Api.Helpers;
-using Jellyfin.Database.Implementations;
using Jellyfin.Drawing;
using Jellyfin.MediaEncoding.Hls.Playlist;
using Jellyfin.Networking.Manager;
using Jellyfin.Networking.Udp;
+using Jellyfin.Server.Implementations.FullSystemBackup;
using Jellyfin.Server.Implementations.Item;
using Jellyfin.Server.Implementations.MediaSegments;
+using Jellyfin.Server.Implementations.SystemBackupService;
using MediaBrowser.Common;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Events;
@@ -57,11 +59,13 @@ using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.Lyrics;
using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Controller.MediaSegments;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Playlists;
@@ -92,7 +96,6 @@ using MediaBrowser.Providers.Subtitles;
using MediaBrowser.XbmcMetadata.Providers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
@@ -267,6 +270,8 @@ namespace Emby.Server.Implementations
? Environment.MachineName
: ConfigurationManager.Configuration.ServerName;
+ public string RestoreBackupPath { get; set; }
+
public string ExpandVirtualPath(string path)
{
if (path is null)
@@ -471,6 +476,7 @@ namespace Emby.Server.Implementations
serviceCollection.AddSingleton<IApplicationHost>(this);
serviceCollection.AddSingleton<IPluginManager>(_pluginManager);
serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
+ serviceCollection.AddSingleton<IBackupService, BackupService>();
serviceCollection.AddSingleton<IFileSystem, ManagedFileSystem>();
serviceCollection.AddSingleton<IShortcutHandler, MbLinkShortcutHandler>();
@@ -505,11 +511,13 @@ namespace Emby.Server.Implementations
serviceCollection.AddSingleton<IChapterRepository, ChapterRepository>();
serviceCollection.AddSingleton<IMediaAttachmentRepository, MediaAttachmentRepository>();
serviceCollection.AddSingleton<IMediaStreamRepository, MediaStreamRepository>();
+ serviceCollection.AddSingleton<IKeyframeRepository, KeyframeRepository>();
serviceCollection.AddSingleton<IItemTypeLookup, ItemTypeLookup>();
serviceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
serviceCollection.AddSingleton<EncodingHelper>();
serviceCollection.AddSingleton<IPathManager, PathManager>();
+ serviceCollection.AddSingleton<IExternalDataManager, ExternalDataManager>();
// TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
@@ -551,13 +559,14 @@ namespace Emby.Server.Implementations
serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
- serviceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
+ serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
serviceCollection.AddSingleton<IAuthService, AuthService>();
serviceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
serviceCollection.AddSingleton<ISubtitleParser, SubtitleEditParser>();
serviceCollection.AddSingleton<ISubtitleEncoder, SubtitleEncoder>();
+ serviceCollection.AddSingleton<IKeyframeManager, KeyframeManager>();
serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
@@ -578,21 +587,6 @@ namespace Emby.Server.Implementations
/// <returns>A task representing the service initialization operation.</returns>
public async Task InitializeServices(IConfiguration startupConfig)
{
- var factory = Resolve<IDbContextFactory<JellyfinDbContext>>();
- var provider = Resolve<IJellyfinDatabaseProvider>();
- provider.DbContextFactory = factory;
-
- var jellyfinDb = await factory.CreateDbContextAsync().ConfigureAwait(false);
- await using (jellyfinDb.ConfigureAwait(false))
- {
- if ((await jellyfinDb.Database.GetPendingMigrationsAsync().ConfigureAwait(false)).Any())
- {
- Logger.LogInformation("There are pending EFCore migrations in the database. Applying... (This may take a while, do not stop Jellyfin)");
- await jellyfinDb.Database.MigrateAsync().ConfigureAwait(false);
- Logger.LogInformation("EFCore migrations applied successfully");
- }
- }
-
var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
await localizationManager.LoadAll().ConfigureAwait(false);
@@ -640,24 +634,25 @@ namespace Emby.Server.Implementations
private void SetStaticProperties()
{
// For now there's no real way to inject these properly
- BaseItem.Logger = Resolve<ILogger<BaseItem>>();
+ BaseItem.ChapterManager = Resolve<IChapterManager>();
+ BaseItem.ChannelManager = Resolve<IChannelManager>();
BaseItem.ConfigurationManager = ConfigurationManager;
+ BaseItem.FileSystem = Resolve<IFileSystem>();
+ BaseItem.ItemRepository = Resolve<IItemRepository>();
BaseItem.LibraryManager = Resolve<ILibraryManager>();
- BaseItem.ProviderManager = Resolve<IProviderManager>();
BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
- BaseItem.ItemRepository = Resolve<IItemRepository>();
- BaseItem.ChapterRepository = Resolve<IChapterRepository>();
- BaseItem.FileSystem = Resolve<IFileSystem>();
- BaseItem.UserDataManager = Resolve<IUserDataManager>();
- BaseItem.ChannelManager = Resolve<IChannelManager>();
- Video.RecordingsManager = Resolve<IRecordingsManager>();
- Folder.UserViewManager = Resolve<IUserViewManager>();
- UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
- UserView.CollectionManager = Resolve<ICollectionManager>();
- BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
+ BaseItem.Logger = Resolve<ILogger<BaseItem>>();
BaseItem.MediaSegmentManager = Resolve<IMediaSegmentManager>();
+ BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
+ BaseItem.ProviderManager = Resolve<IProviderManager>();
+ BaseItem.UserDataManager = Resolve<IUserDataManager>();
CollectionFolder.XmlSerializer = _xmlSerializer;
CollectionFolder.ApplicationHost = this;
+ Folder.UserViewManager = Resolve<IUserViewManager>();
+ Folder.CollectionManager = Resolve<ICollectionManager>();
+ Episode.MediaEncoder = Resolve<IMediaEncoder>();
+ UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
+ Video.RecordingsManager = Resolve<IRecordingsManager>();
}
/// <summary>
diff --git a/Emby.Server.Implementations/Chapters/ChapterManager.cs b/Emby.Server.Implementations/Chapters/ChapterManager.cs
new file mode 100644
index 000000000..b4daa2a14
--- /dev/null
+++ b/Emby.Server.Implementations/Chapters/ChapterManager.cs
@@ -0,0 +1,313 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Extensions;
+using MediaBrowser.Controller.Chapters;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Controller.Persistence;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.MediaInfo;
+using Microsoft.Extensions.Logging;
+
+namespace Emby.Server.Implementations.Chapters;
+
+/// <summary>
+/// The chapter manager.
+/// </summary>
+public class ChapterManager : IChapterManager
+{
+ private readonly IFileSystem _fileSystem;
+ private readonly ILogger<ChapterManager> _logger;
+ private readonly IMediaEncoder _encoder;
+ private readonly IChapterRepository _chapterRepository;
+ private readonly ILibraryManager _libraryManager;
+ private readonly IPathManager _pathManager;
+
+ /// <summary>
+ /// The first chapter ticks.
+ /// </summary>
+ private static readonly long _firstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ChapterManager"/> class.
+ /// </summary>
+ /// <param name="logger">The <see cref="ILogger{ChapterManager}"/>.</param>
+ /// <param name="fileSystem">The <see cref="IFileSystem"/>.</param>
+ /// <param name="encoder">The <see cref="IMediaEncoder"/>.</param>
+ /// <param name="chapterRepository">The <see cref="IChapterRepository"/>.</param>
+ /// <param name="libraryManager">The <see cref="ILibraryManager"/>.</param>
+ /// <param name="pathManager">The <see cref="IPathManager"/>.</param>
+ public ChapterManager(
+ ILogger<ChapterManager> logger,
+ IFileSystem fileSystem,
+ IMediaEncoder encoder,
+ IChapterRepository chapterRepository,
+ ILibraryManager libraryManager,
+ IPathManager pathManager)
+ {
+ _logger = logger;
+ _fileSystem = fileSystem;
+ _encoder = encoder;
+ _chapterRepository = chapterRepository;
+ _libraryManager = libraryManager;
+ _pathManager = pathManager;
+ }
+
+ /// <summary>
+ /// Determines whether [is eligible for chapter image extraction] [the specified video].
+ /// </summary>
+ /// <param name="video">The video.</param>
+ /// <param name="libraryOptions">The library options for the video.</param>
+ /// <returns><c>true</c> if [is eligible for chapter image extraction] [the specified video]; otherwise, <c>false</c>.</returns>
+ private bool IsEligibleForChapterImageExtraction(Video video, LibraryOptions libraryOptions)
+ {
+ if (video.IsPlaceHolder)
+ {
+ return false;
+ }
+
+ if (libraryOptions is null || !libraryOptions.EnableChapterImageExtraction)
+ {
+ return false;
+ }
+
+ if (video.IsShortcut)
+ {
+ return false;
+ }
+
+ if (!video.IsCompleteMedia)
+ {
+ return false;
+ }
+
+ // Can't extract images if there are no video streams
+ return video.DefaultVideoStreamIndex.HasValue;
+ }
+
+ private long GetAverageDurationBetweenChapters(IReadOnlyList<ChapterInfo> chapters)
+ {
+ if (chapters.Count < 2)
+ {
+ return 0;
+ }
+
+ long sum = 0;
+ for (int i = 1; i < chapters.Count; i++)
+ {
+ sum += chapters[i].StartPositionTicks - chapters[i - 1].StartPositionTicks;
+ }
+
+ return sum / chapters.Count;
+ }
+
+ /// <inheritdoc />
+ public async Task<bool> RefreshChapterImages(Video video, IDirectoryService directoryService, IReadOnlyList<ChapterInfo> chapters, bool extractImages, bool saveChapters, CancellationToken cancellationToken)
+ {
+ if (chapters.Count == 0)
+ {
+ return true;
+ }
+
+ var libraryOptions = _libraryManager.GetLibraryOptions(video);
+
+ if (!IsEligibleForChapterImageExtraction(video, libraryOptions))
+ {
+ extractImages = false;
+ }
+
+ var averageChapterDuration = GetAverageDurationBetweenChapters(chapters);
+ var threshold = TimeSpan.FromSeconds(1).Ticks;
+ if (averageChapterDuration < threshold)
+ {
+ _logger.LogInformation("Skipping chapter image extraction for {Video} as the average chapter duration {AverageDuration} was lower than the minimum threshold {Threshold}", video.Name, averageChapterDuration, threshold);
+ extractImages = false;
+ }
+
+ var success = true;
+ var changesMade = false;
+
+ var runtimeTicks = video.RunTimeTicks ?? 0;
+
+ var currentImages = GetSavedChapterImages(video, directoryService);
+
+ foreach (var chapter in chapters)
+ {
+ if (chapter.StartPositionTicks >= runtimeTicks)
+ {
+ _logger.LogInformation("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
+ break;
+ }
+
+ var path = _pathManager.GetChapterImagePath(video, chapter.StartPositionTicks);
+
+ if (!currentImages.Contains(path, StringComparison.OrdinalIgnoreCase))
+ {
+ if (extractImages)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ try
+ {
+ // Add some time for the first chapter to make sure we don't end up with a black image
+ var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(_firstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
+
+ var inputPath = video.Path;
+ var directoryPath = Path.GetDirectoryName(path);
+ if (!string.IsNullOrEmpty(directoryPath))
+ {
+ Directory.CreateDirectory(directoryPath);
+ }
+
+ var container = video.Container;
+ var mediaSource = new MediaSourceInfo
+ {
+ VideoType = video.VideoType,
+ IsoType = video.IsoType,
+ Protocol = video.PathProtocol ?? MediaProtocol.File,
+ };
+
+ _logger.LogInformation("Extracting chapter image for {Name} at {Path}", video.Name, inputPath);
+ var tempFile = await _encoder.ExtractVideoImage(inputPath, container, mediaSource, video.GetDefaultVideoStream(), video.Video3DFormat, time, cancellationToken).ConfigureAwait(false);
+ File.Copy(tempFile, path, true);
+
+ try
+ {
+ _fileSystem.DeleteFile(tempFile);
+ }
+ catch (IOException ex)
+ {
+ _logger.LogError(ex, "Error deleting temporary chapter image encoding file {Path}", tempFile);
+ }
+
+ chapter.ImagePath = path;
+ chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
+ changesMade = true;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error extracting chapter images for {0}", string.Join(',', video.Path));
+ success = false;
+ break;
+ }
+ }
+ else if (!string.IsNullOrEmpty(chapter.ImagePath))
+ {
+ chapter.ImagePath = null;
+ changesMade = true;
+ }
+ }
+ else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
+ {
+ chapter.ImagePath = path;
+ chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
+ changesMade = true;
+ }
+ else if (libraryOptions?.EnableChapterImageExtraction != true)
+ {
+ // We have an image for the current chapter but the user has disabled chapter image extraction -> delete this chapter's image
+ chapter.ImagePath = null;
+ changesMade = true;
+ }
+ }
+
+ if (saveChapters && changesMade)
+ {
+ _chapterRepository.SaveChapters(video.Id, chapters);
+ }
+
+ DeleteDeadImages(currentImages, chapters);
+
+ return success;
+ }
+
+ /// <inheritdoc />
+ public void SaveChapters(Video video, IReadOnlyList<ChapterInfo> chapters)
+ {
+ _chapterRepository.SaveChapters(video.Id, chapters);
+ }
+
+ /// <inheritdoc />
+ public ChapterInfo? GetChapter(Guid baseItemId, int index)
+ {
+ return _chapterRepository.GetChapter(baseItemId, index);
+ }
+
+ /// <inheritdoc />
+ public IReadOnlyList<ChapterInfo> GetChapters(Guid baseItemId)
+ {
+ return _chapterRepository.GetChapters(baseItemId);
+ }
+
+ /// <inheritdoc />
+ public void DeleteChapterImages(Video video)
+ {
+ var path = _pathManager.GetChapterImageFolderPath(video);
+ try
+ {
+ if (Directory.Exists(path))
+ {
+ _logger.LogInformation("Removing chapter images for {Name} [{Id}]", video.Name, video.Id);
+ Directory.Delete(path, true);
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning("Failed to remove chapter image folder for {Item}: {Exception}", video.Id, ex);
+ }
+
+ _chapterRepository.DeleteChapters(video.Id);
+ }
+
+ private IReadOnlyList<string> GetSavedChapterImages(Video video, IDirectoryService directoryService)
+ {
+ var path = _pathManager.GetChapterImageFolderPath(video);
+ if (!Directory.Exists(path))
+ {
+ return [];
+ }
+
+ try
+ {
+ return directoryService.GetFilePaths(path);
+ }
+ catch (IOException)
+ {
+ return [];
+ }
+ }
+
+ private void DeleteDeadImages(IEnumerable<string> images, IEnumerable<ChapterInfo> chapters)
+ {
+ var existingImages = chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i));
+ var deadImages = images
+ .Except(existingImages, StringComparer.OrdinalIgnoreCase)
+ .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i.AsSpan()), StringComparison.OrdinalIgnoreCase))
+ .ToList();
+
+ foreach (var image in deadImages)
+ {
+ _logger.LogDebug("Deleting dead chapter image {Path}", image);
+
+ try
+ {
+ _fileSystem.DeleteFile(image!);
+ }
+ catch (IOException ex)
+ {
+ _logger.LogError(ex, "Error deleting {Path}.", image);
+ }
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs
index 60f515f24..0eb387ffd 100644
--- a/Emby.Server.Implementations/Collections/CollectionManager.cs
+++ b/Emby.Server.Implementations/Collections/CollectionManager.cs
@@ -95,7 +95,7 @@ namespace Emby.Server.Implementations.Collections
var libraryOptions = new LibraryOptions
{
- PathInfos = new[] { new MediaPathInfo(path) },
+ PathInfos = [new MediaPathInfo(path)],
EnableRealtimeMonitor = false,
SaveLocalMetadata = true
};
@@ -150,15 +150,15 @@ namespace Emby.Server.Implementations.Collections
try
{
- Directory.CreateDirectory(path);
-
+ var info = Directory.CreateDirectory(path);
var collection = new BoxSet
{
Name = name,
Path = path,
IsLocked = options.IsLocked,
ProviderIds = options.ProviderIds,
- DateCreated = DateTime.UtcNow
+ DateCreated = info.CreationTimeUtc,
+ DateModified = info.LastWriteTimeUtc
};
parentFolder.AddChild(collection);
diff --git a/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs b/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs
index 63481b1f8..31ae82d6a 100644
--- a/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs
+++ b/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs
@@ -1,14 +1,14 @@
#pragma warning disable CS1591
using System;
+using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Database.Implementations;
-using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Trickplay;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
@@ -19,15 +19,18 @@ public class CleanDatabaseScheduledTask : ILibraryPostScanTask
private readonly ILibraryManager _libraryManager;
private readonly ILogger<CleanDatabaseScheduledTask> _logger;
private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
+ private readonly IPathManager _pathManager;
public CleanDatabaseScheduledTask(
ILibraryManager libraryManager,
ILogger<CleanDatabaseScheduledTask> logger,
- IDbContextFactory<JellyfinDbContext> dbProvider)
+ IDbContextFactory<JellyfinDbContext> dbProvider,
+ IPathManager pathManager)
{
_libraryManager = libraryManager;
_logger = logger;
_dbProvider = dbProvider;
+ _pathManager = pathManager;
}
public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
@@ -45,7 +48,7 @@ public class CleanDatabaseScheduledTask : ILibraryPostScanTask
var numComplete = 0;
var numItems = itemIds.Count + 1;
- _logger.LogDebug("Cleaning {Number} items with dead parent links", numItems);
+ _logger.LogDebug("Cleaning {Number} items with dead parents", numItems);
foreach (var itemId in itemIds)
{
@@ -56,6 +59,33 @@ public class CleanDatabaseScheduledTask : ILibraryPostScanTask
{
_logger.LogInformation("Cleaning item {Item} type: {Type} path: {Path}", item.Name, item.GetType().Name, item.Path ?? string.Empty);
+ foreach (var mediaSource in item.GetMediaSources(false))
+ {
+ // Delete extracted data
+ var mediaSourceItem = _libraryManager.GetItemById(mediaSource.Id);
+ if (mediaSourceItem is null)
+ {
+ continue;
+ }
+
+ var extractedDataFolders = _pathManager.GetExtractedDataPaths(mediaSourceItem);
+ foreach (var folder in extractedDataFolders)
+ {
+ if (Directory.Exists(folder))
+ {
+ try
+ {
+ Directory.Delete(folder, true);
+ }
+ catch (Exception e)
+ {
+ _logger.LogWarning("Failed to remove {Folder}: {Exception}", folder, e.Message);
+ }
+ }
+ }
+ }
+
+ // Delete item
_libraryManager.DeleteItem(item, new DeleteOptions
{
DeleteFileLocation = false
diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs
index 0ce967e6a..9e0a6080d 100644
--- a/Emby.Server.Implementations/Dto/DtoService.cs
+++ b/Emby.Server.Implementations/Dto/DtoService.cs
@@ -17,7 +17,6 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Trickplay;
@@ -41,7 +40,6 @@ namespace Emby.Server.Implementations.Dto
private readonly ILogger<DtoService> _logger;
private readonly ILibraryManager _libraryManager;
private readonly IUserDataManager _userDataRepository;
- private readonly IItemRepository _itemRepo;
private readonly IImageProcessor _imageProcessor;
private readonly IProviderManager _providerManager;
@@ -52,13 +50,12 @@ namespace Emby.Server.Implementations.Dto
private readonly Lazy<ILiveTvManager> _livetvManagerFactory;
private readonly ITrickplayManager _trickplayManager;
- private readonly IChapterRepository _chapterRepository;
+ private readonly IChapterManager _chapterManager;
public DtoService(
ILogger<DtoService> logger,
ILibraryManager libraryManager,
IUserDataManager userDataRepository,
- IItemRepository itemRepo,
IImageProcessor imageProcessor,
IProviderManager providerManager,
IRecordingsManager recordingsManager,
@@ -66,12 +63,11 @@ namespace Emby.Server.Implementations.Dto
IMediaSourceManager mediaSourceManager,
Lazy<ILiveTvManager> livetvManagerFactory,
ITrickplayManager trickplayManager,
- IChapterRepository chapterRepository)
+ IChapterManager chapterManager)
{
_logger = logger;
_libraryManager = libraryManager;
_userDataRepository = userDataRepository;
- _itemRepo = itemRepo;
_imageProcessor = imageProcessor;
_providerManager = providerManager;
_recordingsManager = recordingsManager;
@@ -79,7 +75,7 @@ namespace Emby.Server.Implementations.Dto
_mediaSourceManager = mediaSourceManager;
_livetvManagerFactory = livetvManagerFactory;
_trickplayManager = trickplayManager;
- _chapterRepository = chapterRepository;
+ _chapterManager = chapterManager;
}
private ILiveTvManager LivetvManager => _livetvManagerFactory.Value;
@@ -99,11 +95,11 @@ namespace Emby.Server.Implementations.Dto
if (item is LiveTvChannel tvChannel)
{
- (channelTuples ??= new()).Add((dto, tvChannel));
+ (channelTuples ??= []).Add((dto, tvChannel));
}
else if (item is LiveTvProgram)
{
- (programTuples ??= new()).Add((item, dto));
+ (programTuples ??= []).Add((item, dto));
}
if (item is IItemByName byName)
@@ -590,12 +586,12 @@ namespace Emby.Server.Implementations.Dto
if (dto.ImageBlurHashes is not null)
{
// Only add BlurHash for the person's image.
- baseItemPerson.ImageBlurHashes = new Dictionary<ImageType, Dictionary<string, string>>();
+ baseItemPerson.ImageBlurHashes = [];
foreach (var (imageType, blurHash) in dto.ImageBlurHashes)
{
if (blurHash is not null)
{
- baseItemPerson.ImageBlurHashes[imageType] = new Dictionary<string, string>();
+ baseItemPerson.ImageBlurHashes[imageType] = [];
foreach (var (imageId, blurHashValue) in blurHash)
{
if (string.Equals(baseItemPerson.PrimaryImageTag, imageId, StringComparison.OrdinalIgnoreCase))
@@ -674,11 +670,11 @@ namespace Emby.Server.Implementations.Dto
if (!string.IsNullOrEmpty(image.BlurHash))
{
- dto.ImageBlurHashes ??= new Dictionary<ImageType, Dictionary<string, string>>();
+ dto.ImageBlurHashes ??= [];
if (!dto.ImageBlurHashes.TryGetValue(image.Type, out var value))
{
- value = new Dictionary<string, string>();
+ value = [];
dto.ImageBlurHashes[image.Type] = value;
}
@@ -709,7 +705,7 @@ namespace Emby.Server.Implementations.Dto
if (hashes.Count > 0)
{
- dto.ImageBlurHashes ??= new Dictionary<ImageType, Dictionary<string, string>>();
+ dto.ImageBlurHashes ??= [];
dto.ImageBlurHashes[imageType] = hashes;
}
@@ -756,7 +752,7 @@ namespace Emby.Server.Implementations.Dto
dto.AspectRatio = hasAspectRatio.AspectRatio;
}
- dto.ImageBlurHashes = new Dictionary<ImageType, Dictionary<string, string>>();
+ dto.ImageBlurHashes = [];
var backdropLimit = options.GetImageLimit(ImageType.Backdrop);
if (backdropLimit > 0)
@@ -772,7 +768,7 @@ namespace Emby.Server.Implementations.Dto
if (options.EnableImages)
{
- dto.ImageTags = new Dictionary<ImageType, string>();
+ dto.ImageTags = [];
// Prevent implicitly captured closure
var currentItem = item;
@@ -1064,7 +1060,7 @@ namespace Emby.Server.Implementations.Dto
if (options.ContainsField(ItemFields.Chapters))
{
- dto.Chapters = _chapterRepository.GetChapters(item.Id).ToList();
+ dto.Chapters = _chapterManager.GetChapters(item.Id).ToList();
}
if (options.ContainsField(ItemFields.Trickplay))
diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj
index 6722c20da..15843730e 100644
--- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj
+++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj
@@ -65,9 +65,13 @@
</ItemGroup>
<ItemGroup>
+ <PackageReference Include="Ignore" />
+ </ItemGroup>
+
+ <ItemGroup>
<EmbeddedResource Include="Localization\iso6392.txt" />
<EmbeddedResource Include="Localization\countries.json" />
<EmbeddedResource Include="Localization\Core\*.json" />
- <EmbeddedResource Include="Localization\Ratings\*.csv" />
+ <EmbeddedResource Include="Localization\Ratings\*.json" />
</ItemGroup>
</Project>
diff --git a/Emby.Server.Implementations/IO/FileRefresher.cs b/Emby.Server.Implementations/IO/FileRefresher.cs
index 7378cf885..f63408403 100644
--- a/Emby.Server.Implementations/IO/FileRefresher.cs
+++ b/Emby.Server.Implementations/IO/FileRefresher.cs
@@ -130,7 +130,7 @@ namespace Emby.Server.Implementations.IO
private void ProcessPathChanges(List<string> paths)
{
IEnumerable<BaseItem> itemsToRefresh = paths
- .Distinct(StringComparer.OrdinalIgnoreCase)
+ .Distinct()
.Select(GetAffectedBaseItem)
.Where(item => item is not null)
.DistinctBy(x => x!.Id)!; // Removed null values in the previous .Where()
diff --git a/Emby.Server.Implementations/IO/LibraryMonitor.cs b/Emby.Server.Implementations/IO/LibraryMonitor.cs
index 6af2a553d..d87ad729e 100644
--- a/Emby.Server.Implementations/IO/LibraryMonitor.cs
+++ b/Emby.Server.Implementations/IO/LibraryMonitor.cs
@@ -121,7 +121,7 @@ namespace Emby.Server.Implementations.IO
.Where(IsLibraryMonitorEnabled)
.OfType<Folder>()
.SelectMany(f => f.PhysicalLocations)
- .Distinct(StringComparer.OrdinalIgnoreCase)
+ .Distinct()
.Order();
foreach (var path in paths)
diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs
index ac5933a69..c9630b894 100644
--- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs
+++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs
@@ -160,12 +160,13 @@ namespace Emby.Server.Implementations.IO
{
// Cross device move requires a copy
Directory.CreateDirectory(destination);
- foreach (string file in Directory.GetFiles(source))
+ var sourceDir = new DirectoryInfo(source);
+ foreach (var file in sourceDir.EnumerateFiles())
{
- File.Copy(file, Path.Combine(destination, Path.GetFileName(file)), true);
+ file.CopyTo(Path.Combine(destination, file.Name), true);
}
- Directory.Delete(source, true);
+ sourceDir.Delete(true);
}
}
diff --git a/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs b/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs
index b01fd93a7..f29a0b3ad 100644
--- a/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs
+++ b/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs
@@ -54,7 +54,7 @@ namespace Emby.Server.Implementations.Library
{
if (parent is not null)
{
- // Ignore extras folders but allow it at the collection level
+ // Ignore extras for unsupported types
if (_namingOptions.AllExtrasTypesFolderNames.ContainsKey(filename)
&& parent is not AggregateFolder
&& parent is not UserRootFolder)
@@ -67,7 +67,7 @@ namespace Emby.Server.Implementations.Library
{
if (parent is not null)
{
- // Don't resolve these into audio files
+ // Don't resolve theme songs
if (Path.GetFileNameWithoutExtension(filename.AsSpan()).Equals(BaseItem.ThemeSongFileName, StringComparison.Ordinal)
&& AudioFileParser.IsAudioFile(filename, _namingOptions))
{
diff --git a/Emby.Server.Implementations/Library/DotIgnoreIgnoreRule.cs b/Emby.Server.Implementations/Library/DotIgnoreIgnoreRule.cs
new file mode 100644
index 000000000..b0ed1de8d
--- /dev/null
+++ b/Emby.Server.Implementations/Library/DotIgnoreIgnoreRule.cs
@@ -0,0 +1,77 @@
+using System;
+using System.IO;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Resolvers;
+using MediaBrowser.Model.IO;
+
+namespace Emby.Server.Implementations.Library;
+
+/// <summary>
+/// Resolver rule class for ignoring files via .ignore.
+/// </summary>
+public class DotIgnoreIgnoreRule : IResolverIgnoreRule
+{
+ private static FileInfo? FindIgnoreFile(DirectoryInfo directory)
+ {
+ var ignoreFile = new FileInfo(Path.Join(directory.FullName, ".ignore"));
+ if (ignoreFile.Exists)
+ {
+ return ignoreFile;
+ }
+
+ var parentDir = directory.Parent;
+ if (parentDir is null)
+ {
+ return null;
+ }
+
+ return FindIgnoreFile(parentDir);
+ }
+
+ /// <inheritdoc />
+ public bool ShouldIgnore(FileSystemMetadata fileInfo, BaseItem? parent)
+ {
+ return IsIgnored(fileInfo, parent);
+ }
+
+ /// <summary>
+ /// Checks whether or not the file is ignored.
+ /// </summary>
+ /// <param name="fileInfo">The file information.</param>
+ /// <param name="parent">The parent BaseItem.</param>
+ /// <returns>True if the file should be ignored.</returns>
+ public static bool IsIgnored(FileSystemMetadata fileInfo, BaseItem? parent)
+ {
+ var parentDirPath = Path.GetDirectoryName(fileInfo.FullName);
+ if (string.IsNullOrEmpty(parentDirPath))
+ {
+ return false;
+ }
+
+ var folder = new DirectoryInfo(parentDirPath);
+ var ignoreFile = FindIgnoreFile(folder);
+ if (ignoreFile is null)
+ {
+ return false;
+ }
+
+ string ignoreFileString;
+ using (var reader = ignoreFile.OpenText())
+ {
+ ignoreFileString = reader.ReadToEnd();
+ }
+
+ if (string.IsNullOrEmpty(ignoreFileString))
+ {
+ // Ignore directory if we just have the file
+ return true;
+ }
+
+ // If file has content, base ignoring off the content .gitignore-style rules
+ var ignoreRules = ignoreFileString.Split('\n', StringSplitOptions.RemoveEmptyEntries);
+ var ignore = new Ignore.Ignore();
+ ignore.Add(ignoreRules);
+
+ return ignore.IsIgnored(fileInfo.FullName);
+ }
+}
diff --git a/Emby.Server.Implementations/Library/ExternalDataManager.cs b/Emby.Server.Implementations/Library/ExternalDataManager.cs
new file mode 100644
index 000000000..68e3aaff4
--- /dev/null
+++ b/Emby.Server.Implementations/Library/ExternalDataManager.cs
@@ -0,0 +1,58 @@
+using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
+using MediaBrowser.Controller.MediaSegments;
+using MediaBrowser.Controller.Trickplay;
+
+namespace Emby.Server.Implementations.Library;
+
+/// <summary>
+/// IExternalDataManager implementation.
+/// </summary>
+public class ExternalDataManager : IExternalDataManager
+{
+ private readonly IKeyframeManager _keyframeManager;
+ private readonly IMediaSegmentManager _mediaSegmentManager;
+ private readonly IPathManager _pathManager;
+ private readonly ITrickplayManager _trickplayManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExternalDataManager"/> class.
+ /// </summary>
+ /// <param name="keyframeManager">The keyframe manager.</param>
+ /// <param name="mediaSegmentManager">The media segment manager.</param>
+ /// <param name="pathManager">The path manager.</param>
+ /// <param name="trickplayManager">The trickplay manager.</param>
+ public ExternalDataManager(
+ IKeyframeManager keyframeManager,
+ IMediaSegmentManager mediaSegmentManager,
+ IPathManager pathManager,
+ ITrickplayManager trickplayManager)
+ {
+ _keyframeManager = keyframeManager;
+ _mediaSegmentManager = mediaSegmentManager;
+ _pathManager = pathManager;
+ _trickplayManager = trickplayManager;
+ }
+
+ /// <inheritdoc/>
+ public async Task DeleteExternalItemDataAsync(BaseItem item, CancellationToken cancellationToken)
+ {
+ var validPaths = _pathManager.GetExtractedDataPaths(item).Where(Directory.Exists).ToList();
+ var itemId = item.Id;
+ if (validPaths.Count > 0)
+ {
+ foreach (var path in validPaths)
+ {
+ Directory.Delete(path, true);
+ }
+ }
+
+ await _keyframeManager.DeleteKeyframeDataAsync(itemId, cancellationToken).ConfigureAwait(false);
+ await _mediaSegmentManager.DeleteSegmentsAsync(itemId, cancellationToken).ConfigureAwait(false);
+ await _trickplayManager.DeleteTrickplayDataAsync(itemId, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/Emby.Server.Implementations/Library/IgnorePatterns.cs b/Emby.Server.Implementations/Library/IgnorePatterns.cs
index bb45dd87e..25ddade82 100644
--- a/Emby.Server.Implementations/Library/IgnorePatterns.cs
+++ b/Emby.Server.Implementations/Library/IgnorePatterns.cs
@@ -1,5 +1,4 @@
using System;
-using System.Linq;
using DotNet.Globbing;
namespace Emby.Server.Implementations.Library
diff --git a/Emby.Server.Implementations/Library/KeyframeManager.cs b/Emby.Server.Implementations/Library/KeyframeManager.cs
new file mode 100644
index 000000000..18f4ce047
--- /dev/null
+++ b/Emby.Server.Implementations/Library/KeyframeManager.cs
@@ -0,0 +1,44 @@
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.MediaEncoding.Keyframes;
+using MediaBrowser.Controller.IO;
+using MediaBrowser.Controller.Persistence;
+
+namespace Emby.Server.Implementations.Library;
+
+/// <summary>
+/// Manager for Keyframe data.
+/// </summary>
+public class KeyframeManager : IKeyframeManager
+{
+ private readonly IKeyframeRepository _repository;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="KeyframeManager"/> class.
+ /// </summary>
+ /// <param name="repository">The keyframe repository.</param>
+ public KeyframeManager(IKeyframeRepository repository)
+ {
+ _repository = repository;
+ }
+
+ /// <inheritdoc />
+ public IReadOnlyList<KeyframeData> GetKeyframeData(Guid itemId)
+ {
+ return _repository.GetKeyframeData(itemId);
+ }
+
+ /// <inheritdoc />
+ public async Task SaveKeyframeDataAsync(Guid itemId, KeyframeData data, CancellationToken cancellationToken)
+ {
+ await _repository.SaveKeyframeDataAsync(itemId, data, cancellationToken).ConfigureAwait(false);
+ }
+
+ /// <inheritdoc />
+ public async Task DeleteKeyframeDataAsync(Guid itemId, CancellationToken cancellationToken)
+ {
+ await _repository.DeleteKeyframeDataAsync(itemId, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs
index c8026960d..d03c614cf 100644
--- a/Emby.Server.Implementations/Library/LibraryManager.cs
+++ b/Emby.Server.Implementations/Library/LibraryManager.cs
@@ -34,10 +34,12 @@ using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Controller.MediaSegments;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Resolvers;
using MediaBrowser.Controller.Sorting;
+using MediaBrowser.Controller.Trickplay;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Drawing;
@@ -66,11 +68,11 @@ namespace Emby.Server.Implementations.Library
private readonly ILogger<LibraryManager> _logger;
private readonly ITaskManager _taskManager;
private readonly IUserManager _userManager;
- private readonly IUserDataManager _userDataRepository;
+ private readonly IUserDataManager _userDataManager;
private readonly IServerConfigurationManager _configurationManager;
private readonly Lazy<ILibraryMonitor> _libraryMonitorFactory;
private readonly Lazy<IProviderManager> _providerManagerFactory;
- private readonly Lazy<IUserViewManager> _userviewManagerFactory;
+ private readonly Lazy<IUserViewManager> _userViewManagerFactory;
private readonly IServerApplicationHost _appHost;
private readonly IMediaEncoder _mediaEncoder;
private readonly IFileSystem _fileSystem;
@@ -106,11 +108,11 @@ namespace Emby.Server.Implementations.Library
/// <param name="taskManager">The task manager.</param>
/// <param name="userManager">The user manager.</param>
/// <param name="configurationManager">The configuration manager.</param>
- /// <param name="userDataRepository">The user data repository.</param>
+ /// <param name="userDataManager">The user data manager.</param>
/// <param name="libraryMonitorFactory">The library monitor.</param>
/// <param name="fileSystem">The file system.</param>
/// <param name="providerManagerFactory">The provider manager.</param>
- /// <param name="userviewManagerFactory">The userview manager.</param>
+ /// <param name="userViewManagerFactory">The user view manager.</param>
/// <param name="mediaEncoder">The media encoder.</param>
/// <param name="itemRepository">The item repository.</param>
/// <param name="imageProcessor">The image processor.</param>
@@ -124,11 +126,11 @@ namespace Emby.Server.Implementations.Library
ITaskManager taskManager,
IUserManager userManager,
IServerConfigurationManager configurationManager,
- IUserDataManager userDataRepository,
+ IUserDataManager userDataManager,
Lazy<ILibraryMonitor> libraryMonitorFactory,
IFileSystem fileSystem,
Lazy<IProviderManager> providerManagerFactory,
- Lazy<IUserViewManager> userviewManagerFactory,
+ Lazy<IUserViewManager> userViewManagerFactory,
IMediaEncoder mediaEncoder,
IItemRepository itemRepository,
IImageProcessor imageProcessor,
@@ -142,11 +144,11 @@ namespace Emby.Server.Implementations.Library
_taskManager = taskManager;
_userManager = userManager;
_configurationManager = configurationManager;
- _userDataRepository = userDataRepository;
+ _userDataManager = userDataManager;
_libraryMonitorFactory = libraryMonitorFactory;
_fileSystem = fileSystem;
_providerManagerFactory = providerManagerFactory;
- _userviewManagerFactory = userviewManagerFactory;
+ _userViewManagerFactory = userViewManagerFactory;
_mediaEncoder = mediaEncoder;
_itemRepository = itemRepository;
_imageProcessor = imageProcessor;
@@ -202,13 +204,13 @@ namespace Emby.Server.Implementations.Library
private IProviderManager ProviderManager => _providerManagerFactory.Value;
- private IUserViewManager UserViewManager => _userviewManagerFactory.Value;
+ private IUserViewManager UserViewManager => _userViewManagerFactory.Value;
/// <summary>
/// Gets or sets the postscan tasks.
/// </summary>
/// <value>The postscan tasks.</value>
- private ILibraryPostScanTask[] PostscanTasks { get; set; } = [];
+ private ILibraryPostScanTask[] PostScanTasks { get; set; } = [];
/// <summary>
/// Gets or sets the intro providers.
@@ -245,20 +247,20 @@ namespace Emby.Server.Implementations.Library
/// <param name="resolvers">The resolvers.</param>
/// <param name="introProviders">The intro providers.</param>
/// <param name="itemComparers">The item comparers.</param>
- /// <param name="postscanTasks">The post scan tasks.</param>
+ /// <param name="postScanTasks">The post scan tasks.</param>
public void AddParts(
IEnumerable<IResolverIgnoreRule> rules,
IEnumerable<IItemResolver> resolvers,
IEnumerable<IIntroProvider> introProviders,
IEnumerable<IBaseItemComparer> itemComparers,
- IEnumerable<ILibraryPostScanTask> postscanTasks)
+ IEnumerable<ILibraryPostScanTask> postScanTasks)
{
EntityResolutionIgnoreRules = rules.ToArray();
EntityResolvers = resolvers.OrderBy(i => i.Priority).ToArray();
MultiItemResolvers = EntityResolvers.OfType<IMultiItemResolver>().ToArray();
IntroProviders = introProviders.ToArray();
Comparers = itemComparers.ToArray();
- PostscanTasks = postscanTasks.ToArray();
+ PostScanTasks = postScanTasks.ToArray();
}
/// <summary>
@@ -393,7 +395,7 @@ namespace Emby.Server.Implementations.Library
}
}
- if (options.DeleteFileLocation && item.IsFileProtocol)
+ if ((options.DeleteFileLocation && item.IsFileProtocol) || IsInternalItem(item))
{
// Assume only the first is required
// Add this flag to GetDeletePaths if required in the future
@@ -472,6 +474,36 @@ namespace Emby.Server.Implementations.Library
ReportItemRemoved(item, parent);
}
+ private bool IsInternalItem(BaseItem item)
+ {
+ if (!item.IsFileProtocol)
+ {
+ return false;
+ }
+
+ var pathToCheck = item switch
+ {
+ Genre => _configurationManager.ApplicationPaths.GenrePath,
+ MusicArtist => _configurationManager.ApplicationPaths.ArtistsPath,
+ MusicGenre => _configurationManager.ApplicationPaths.GenrePath,
+ Person => _configurationManager.ApplicationPaths.PeoplePath,
+ Studio => _configurationManager.ApplicationPaths.StudioPath,
+ Year => _configurationManager.ApplicationPaths.YearPath,
+ _ => null
+ };
+
+ var itemPath = item.Path;
+ if (!string.IsNullOrEmpty(pathToCheck) && !string.IsNullOrEmpty(itemPath))
+ {
+ var cleanPath = _fileSystem.GetValidFilename(itemPath);
+ var cleanCheckPath = _fileSystem.GetValidFilename(pathToCheck);
+
+ return cleanPath.StartsWith(cleanCheckPath, StringComparison.Ordinal);
+ }
+
+ return false;
+ }
+
private List<string> GetMetadataPaths(BaseItem item, IEnumerable<BaseItem> children)
{
var list = GetInternalMetadataPaths(item);
@@ -492,7 +524,24 @@ namespace Emby.Server.Implementations.Library
if (item is Video video)
{
+ // Trickplay
list.Add(_pathManager.GetTrickplayDirectory(video));
+
+ // Subtitles and attachments
+ foreach (var mediaSource in item.GetMediaSources(false))
+ {
+ var subtitleFolder = _pathManager.GetSubtitleFolderPath(mediaSource.Id);
+ if (subtitleFolder is not null)
+ {
+ list.Add(subtitleFolder);
+ }
+
+ var attachmentFolder = _pathManager.GetAttachmentFolderPath(mediaSource.Id);
+ if (attachmentFolder is not null)
+ {
+ list.Add(attachmentFolder);
+ }
+ }
}
return list;
@@ -622,7 +671,7 @@ namespace Emby.Server.Implementations.Library
}
}
- // Need to remove subpaths that may have been resolved from shortcuts
+ // Need to remove sub-paths that may have been resolved from shortcuts
// Example: if \\server\movies exists, then strip out \\server\movies\action
if (isPhysicalRoot)
{
@@ -632,10 +681,11 @@ namespace Emby.Server.Implementations.Library
args.FileSystemChildren = files;
}
- // Check to see if we should resolve based on our contents
- if (args.IsDirectory && !ShouldResolvePathContents(args))
+ // Filter content based on ignore rules
+ if (args.IsDirectory)
{
- return null;
+ var filtered = args.GetActualFileSystemChildren().ToArray();
+ args.FileSystemChildren = filtered ?? [];
}
return ResolveItem(args, resolvers);
@@ -650,10 +700,10 @@ namespace Emby.Server.Implementations.Library
var list = originalList.Where(i => i.IsDirectory)
.Select(i => Path.TrimEndingDirectorySeparator(i.FullName))
- .Distinct(StringComparer.OrdinalIgnoreCase)
+ .Distinct()
.ToList();
- var dupes = list.Where(subPath => !subPath.EndsWith(":\\", StringComparison.OrdinalIgnoreCase) && list.Any(i => _fileSystem.ContainsSubPath(i, subPath)))
+ var dupes = list.Where(subPath => !subPath.EndsWith(":\\", StringComparison.Ordinal) && list.Any(i => _fileSystem.ContainsSubPath(i, subPath)))
.ToList();
foreach (var dupe in dupes)
@@ -661,22 +711,11 @@ namespace Emby.Server.Implementations.Library
_logger.LogInformation("Found duplicate path: {0}", dupe);
}
- var newList = list.Except(dupes, StringComparer.OrdinalIgnoreCase).Select(_fileSystem.GetDirectoryInfo).ToList();
+ var newList = list.Except(dupes, StringComparer.Ordinal).Select(_fileSystem.GetDirectoryInfo).ToList();
newList.AddRange(originalList.Where(i => !i.IsDirectory));
return newList;
}
- /// <summary>
- /// Determines whether a path should be ignored based on its contents - called after the contents have been read.
- /// </summary>
- /// <param name="args">The args.</param>
- /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
- private static bool ShouldResolvePathContents(ItemResolveArgs args)
- {
- // Ignore any folders containing a file called .ignore
- return !args.ContainsFileSystemEntryByName(".ignore");
- }
-
public IEnumerable<BaseItem> ResolvePaths(IEnumerable<FileSystemMetadata> files, IDirectoryService directoryService, Folder parent, LibraryOptions libraryOptions, CollectionType? collectionType = null)
{
return ResolvePaths(files, directoryService, parent, libraryOptions, collectionType, EntityResolvers);
@@ -751,8 +790,6 @@ namespace Emby.Server.Implementations.Library
{
var rootFolderPath = _configurationManager.ApplicationPaths.RootFolderPath;
- Directory.CreateDirectory(rootFolderPath);
-
var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ??
(ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath)) as Folder ?? throw new InvalidOperationException("Something went very wong"))
.DeepCopy<Folder, AggregateFolder>();
@@ -767,11 +804,12 @@ namespace Emby.Server.Implementations.Library
// Add in the plug-in folders
var path = Path.Combine(_configurationManager.ApplicationPaths.DataPath, "playlists");
- Directory.CreateDirectory(path);
-
+ var info = Directory.CreateDirectory(path);
Folder folder = new PlaylistsFolder
{
- Path = path
+ Path = path,
+ DateCreated = info.CreationTimeUtc,
+ DateModified = info.LastWriteTimeUtc,
};
if (folder.Id.IsEmpty())
@@ -857,7 +895,7 @@ namespace Emby.Server.Implementations.Library
{
Path = path,
IsFolder = isFolder,
- OrderBy = new[] { (ItemSortBy.DateCreated, SortOrder.Descending) },
+ OrderBy = [(ItemSortBy.DateCreated, SortOrder.Descending)],
Limit = 1,
DtoOptions = new DtoOptions(true)
};
@@ -963,7 +1001,7 @@ namespace Emby.Server.Implementations.Library
{
var existing = GetItemList(new InternalItemsQuery
{
- IncludeItemTypes = new[] { BaseItemKind.MusicArtist },
+ IncludeItemTypes = [BaseItemKind.MusicArtist],
Name = name,
DtoOptions = options
}).Cast<MusicArtist>()
@@ -982,12 +1020,13 @@ namespace Emby.Server.Implementations.Library
var item = GetItemById(id) as T;
if (item is null)
{
+ var info = Directory.CreateDirectory(path);
item = new T
{
Name = name,
Id = id,
- DateCreated = DateTime.UtcNow,
- DateModified = DateTime.UtcNow,
+ DateCreated = info.CreationTimeUtc,
+ DateModified = info.LastWriteTimeUtc,
Path = path
};
@@ -1113,7 +1152,7 @@ namespace Emby.Server.Implementations.Library
/// <returns>Task.</returns>
private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
{
- var tasks = PostscanTasks.ToList();
+ var tasks = PostScanTasks.ToList();
var numComplete = 0;
var numTasks = tasks.Count;
@@ -1236,7 +1275,7 @@ namespace Emby.Server.Implementations.Library
private CollectionTypeOptions? GetCollectionType(string path)
{
- var files = _fileSystem.GetFilePaths(path, new[] { ".collection" }, true, false);
+ var files = _fileSystem.GetFilePaths(path, [".collection"], true, false);
foreach (ReadOnlySpan<char> file in files)
{
if (Enum.TryParse<CollectionTypeOptions>(Path.GetFileNameWithoutExtension(file), true, out var res))
@@ -1307,7 +1346,7 @@ namespace Emby.Server.Implementations.Library
var parent = GetItemById(query.ParentId);
if (parent is not null)
{
- SetTopParentIdsOrAncestors(query, new[] { parent });
+ SetTopParentIdsOrAncestors(query, [parent]);
}
}
@@ -1338,7 +1377,7 @@ namespace Emby.Server.Implementations.Library
var parent = GetItemById(query.ParentId);
if (parent is not null)
{
- SetTopParentIdsOrAncestors(query, new[] { parent });
+ SetTopParentIdsOrAncestors(query, [parent]);
}
}
@@ -1526,7 +1565,7 @@ namespace Emby.Server.Implementations.Library
var parent = GetItemById(query.ParentId);
if (parent is not null)
{
- SetTopParentIdsOrAncestors(query, new[] { parent });
+ SetTopParentIdsOrAncestors(query, [parent]);
}
}
@@ -1556,7 +1595,7 @@ namespace Emby.Server.Implementations.Library
// Prevent searching in all libraries due to empty filter
if (query.TopParentIds.Length == 0)
{
- query.TopParentIds = new[] { Guid.NewGuid() };
+ query.TopParentIds = [Guid.NewGuid()];
}
}
else
@@ -1567,7 +1606,7 @@ namespace Emby.Server.Implementations.Library
// Prevent searching in all libraries due to empty filter
if (query.AncestorIds.Length == 0)
{
- query.AncestorIds = new[] { Guid.NewGuid() };
+ query.AncestorIds = [Guid.NewGuid()];
}
}
@@ -1596,7 +1635,7 @@ namespace Emby.Server.Implementations.Library
// Prevent searching in all libraries due to empty filter
if (query.TopParentIds.Length == 0)
{
- query.TopParentIds = new[] { Guid.NewGuid() };
+ query.TopParentIds = [Guid.NewGuid()];
}
}
}
@@ -1607,7 +1646,7 @@ namespace Emby.Server.Implementations.Library
{
if (view.ViewType == CollectionType.livetv)
{
- return new[] { view.Id };
+ return [view.Id];
}
// Translate view into folders
@@ -1656,7 +1695,7 @@ namespace Emby.Server.Implementations.Library
var topParent = item.GetTopParent();
if (topParent is not null)
{
- return new[] { topParent.Id };
+ return [topParent.Id];
}
return [];
@@ -1852,7 +1891,7 @@ namespace Emby.Server.Implementations.Library
userComparer.User = user;
userComparer.UserManager = _userManager;
- userComparer.UserDataRepository = _userDataRepository;
+ userComparer.UserDataManager = _userDataManager;
return userComparer;
}
@@ -1863,7 +1902,7 @@ namespace Emby.Server.Implementations.Library
/// <inheritdoc />
public void CreateItem(BaseItem item, BaseItem? parent)
{
- CreateItems(new[] { item }, parent, CancellationToken.None);
+ CreateItems([item], parent, CancellationToken.None);
}
/// <inheritdoc />
@@ -2049,7 +2088,7 @@ namespace Emby.Server.Implementations.Library
/// <inheritdoc />
public Task UpdateItemAsync(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
- => UpdateItemsAsync(new[] { item }, parent, updateReason, cancellationToken);
+ => UpdateItemsAsync([item], parent, updateReason, cancellationToken);
public async Task RunMetadataSavers(BaseItem item, ItemUpdateType updateReason)
{
@@ -2278,13 +2317,13 @@ namespace Emby.Server.Implementations.Library
if (item is null || !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
{
- Directory.CreateDirectory(path);
-
+ var info = Directory.CreateDirectory(path);
item = new UserView
{
Path = path,
Id = id,
- DateCreated = DateTime.UtcNow,
+ DateCreated = info.CreationTimeUtc,
+ DateModified = info.LastWriteTimeUtc,
Name = name,
ViewType = viewType,
ForcedSortName = sortName
@@ -2326,13 +2365,13 @@ namespace Emby.Server.Implementations.Library
if (item is null)
{
- Directory.CreateDirectory(path);
-
+ var info = Directory.CreateDirectory(path);
item = new UserView
{
Path = path,
Id = id,
- DateCreated = DateTime.UtcNow,
+ DateCreated = info.CreationTimeUtc,
+ DateModified = info.LastWriteTimeUtc,
Name = name,
ViewType = viewType,
ForcedSortName = sortName,
@@ -2390,20 +2429,19 @@ namespace Emby.Server.Implementations.Library
if (item is null)
{
- Directory.CreateDirectory(path);
-
+ var info = Directory.CreateDirectory(path);
item = new UserView
{
Path = path,
Id = id,
- DateCreated = DateTime.UtcNow,
+ DateCreated = info.CreationTimeUtc,
+ DateModified = info.LastWriteTimeUtc,
Name = name,
ViewType = viewType,
- ForcedSortName = sortName
+ ForcedSortName = sortName,
+ DisplayParentId = parentId
};
- item.DisplayParentId = parentId;
-
CreateItem(item, null);
isNew = true;
@@ -2460,20 +2498,19 @@ namespace Emby.Server.Implementations.Library
if (item is null)
{
- Directory.CreateDirectory(path);
-
+ var info = Directory.CreateDirectory(path);
item = new UserView
{
Path = path,
Id = id,
- DateCreated = DateTime.UtcNow,
+ DateCreated = info.CreationTimeUtc,
+ DateModified = info.LastWriteTimeUtc,
Name = name,
ViewType = viewType,
- ForcedSortName = sortName
+ ForcedSortName = sortName,
+ DisplayParentId = parentId
};
- item.DisplayParentId = parentId;
-
CreateItem(item, null);
isNew = true;
@@ -2551,7 +2588,6 @@ namespace Emby.Server.Implementations.Library
var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd;
- // TODO nullable - what are we trying to do there with empty episodeInfo?
EpisodeInfo? episodeInfo = null;
if (episode.IsFileProtocol)
{
@@ -2569,44 +2605,12 @@ namespace Emby.Server.Implementations.Library
}
}
- episodeInfo ??= new EpisodeInfo(episode.Path);
-
- try
- {
- var libraryOptions = GetLibraryOptions(episode);
- if (libraryOptions.EnableEmbeddedEpisodeInfos && string.Equals(episodeInfo.Container, "mp4", StringComparison.OrdinalIgnoreCase))
- {
- // Read from metadata
- var mediaInfo = _mediaEncoder.GetMediaInfo(
- new MediaInfoRequest
- {
- MediaSource = episode.GetMediaSources(false)[0],
- MediaType = DlnaProfileType.Video
- },
- CancellationToken.None).GetAwaiter().GetResult();
- if (mediaInfo.ParentIndexNumber > 0)
- {
- episodeInfo.SeasonNumber = mediaInfo.ParentIndexNumber;
- }
-
- if (mediaInfo.IndexNumber > 0)
- {
- episodeInfo.EpisodeNumber = mediaInfo.IndexNumber;
- }
-
- if (!string.IsNullOrEmpty(mediaInfo.ShowName))
- {
- episodeInfo.SeriesName = mediaInfo.ShowName;
- }
- }
- }
- catch (Exception ex)
+ var changed = false;
+ if (episodeInfo is null)
{
- _logger.LogError(ex, "Error reading the episode information with ffprobe. Episode: {EpisodeInfo}", episodeInfo.Path);
+ return changed;
}
- var changed = false;
-
if (episodeInfo.IsByDate)
{
if (episode.IndexNumber.HasValue)
@@ -2709,27 +2713,33 @@ namespace Emby.Server.Implementations.Library
public IEnumerable<BaseItem> FindExtras(BaseItem owner, IReadOnlyList<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
{
+ // Apply .ignore rules
+ var filtered = fileSystemChildren.Where(c => !DotIgnoreIgnoreRule.IsIgnored(c, owner)).ToList();
var ownerVideoInfo = VideoResolver.Resolve(owner.Path, owner.IsFolder, _namingOptions, libraryRoot: owner.ContainingFolderPath);
if (ownerVideoInfo is null)
{
yield break;
}
- var count = fileSystemChildren.Count;
+ var count = filtered.Count;
for (var i = 0; i < count; i++)
{
- var current = fileSystemChildren[i];
+ var current = filtered[i];
if (current.IsDirectory && _namingOptions.AllExtrasTypesFolderNames.ContainsKey(current.Name))
{
var filesInSubFolder = _fileSystem.GetFiles(current.FullName, null, false, false);
- foreach (var file in filesInSubFolder)
+ var filesInSubFolderList = filesInSubFolder.ToList();
+
+ bool subFolderIsMixedFolder = filesInSubFolderList.Count > 1;
+
+ foreach (var file in filesInSubFolderList)
{
if (!_extraResolver.TryGetExtraTypeForOwner(file.FullName, ownerVideoInfo, out var extraType))
{
continue;
}
- var extra = GetExtra(file, extraType.Value);
+ var extra = GetExtra(file, extraType.Value, subFolderIsMixedFolder);
if (extra is not null)
{
yield return extra;
@@ -2738,7 +2748,7 @@ namespace Emby.Server.Implementations.Library
}
else if (!current.IsDirectory && _extraResolver.TryGetExtraTypeForOwner(current.FullName, ownerVideoInfo, out var extraType))
{
- var extra = GetExtra(current, extraType.Value);
+ var extra = GetExtra(current, extraType.Value, false);
if (extra is not null)
{
yield return extra;
@@ -2746,7 +2756,7 @@ namespace Emby.Server.Implementations.Library
}
}
- BaseItem? GetExtra(FileSystemMetadata file, ExtraType extraType)
+ BaseItem? GetExtra(FileSystemMetadata file, ExtraType extraType, bool isInMixedFolder)
{
var extra = ResolvePath(_fileSystem.GetFileInfo(file.FullName), directoryService, _extraResolver.GetResolversForExtraType(extraType));
if (extra is not Video && extra is not Audio)
@@ -2769,6 +2779,7 @@ namespace Emby.Server.Implementations.Library
extra.ParentId = Guid.Empty;
extra.OwnerId = owner.Id;
+ extra.IsInMixedFolder = isInMixedFolder;
return extra;
}
}
@@ -2899,7 +2910,7 @@ namespace Emby.Server.Implementations.Library
throw new ArgumentNullException(nameof(name));
}
- name = _fileSystem.GetValidFilename(name);
+ name = _fileSystem.GetValidFilename(name.Trim());
var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
@@ -2933,7 +2944,7 @@ namespace Emby.Server.Implementations.Library
{
var path = Path.Combine(virtualFolderPath, collectionType.ToString()!.ToLowerInvariant() + ".collection"); // Can't be null with legal values?
- await File.WriteAllBytesAsync(path, []).ConfigureAwait(false);
+ FileHelper.CreateEmpty(path);
}
CollectionFolder.SaveLibraryOptions(virtualFolderPath, options);
@@ -2977,12 +2988,14 @@ namespace Emby.Server.Implementations.Library
if (personEntity is null)
{
var path = Person.GetPath(person.Name);
+ var info = Directory.CreateDirectory(path);
+ var lastWriteTime = info.LastWriteTimeUtc;
personEntity = new Person()
{
Name = person.Name,
Id = GetItemByNameId<Person>(path),
- DateCreated = DateTime.UtcNow,
- DateModified = DateTime.UtcNow,
+ DateCreated = info.CreationTimeUtc,
+ DateModified = lastWriteTime,
Path = path
};
diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs
index afe5b14e9..ab30971e2 100644
--- a/Emby.Server.Implementations/Library/MediaSourceManager.cs
+++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs
@@ -427,6 +427,7 @@ namespace Emby.Server.Implementations.Library
if (source.MediaStreams.Any(i => i.Type == MediaStreamType.Audio && i.Index == index))
{
source.DefaultAudioStreamIndex = index;
+ source.DefaultAudioIndexSource = AudioIndexSource.User;
return;
}
}
@@ -434,6 +435,15 @@ namespace Emby.Server.Implementations.Library
var preferredAudio = NormalizeLanguage(user.AudioLanguagePreference);
source.DefaultAudioStreamIndex = MediaStreamSelector.GetDefaultAudioStreamIndex(source.MediaStreams, preferredAudio, user.PlayDefaultAudioTrack);
+ if (user.PlayDefaultAudioTrack)
+ {
+ source.DefaultAudioIndexSource |= AudioIndexSource.Default;
+ }
+
+ if (preferredAudio.Count > 0)
+ {
+ source.DefaultAudioIndexSource |= AudioIndexSource.Language;
+ }
}
public void SetDefaultAudioAndSubtitleStreamIndices(BaseItem item, MediaSourceInfo source, User user)
@@ -671,17 +681,17 @@ namespace Emby.Server.Implementations.Library
mediaInfo = await _mediaEncoder.GetMediaInfo(
new MediaInfoRequest
- {
- MediaSource = mediaSource,
- MediaType = isAudio ? DlnaProfileType.Audio : DlnaProfileType.Video,
- ExtractChapters = false
- },
+ {
+ MediaSource = mediaSource,
+ MediaType = isAudio ? DlnaProfileType.Audio : DlnaProfileType.Video,
+ ExtractChapters = false
+ },
cancellationToken).ConfigureAwait(false);
if (cacheFilePath is not null)
{
Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
- FileStream createStream = File.Create(cacheFilePath);
+ FileStream createStream = AsyncFile.Create(cacheFilePath);
await using (createStream.ConfigureAwait(false))
{
await JsonSerializer.SerializeAsync(createStream, mediaInfo, _jsonOptions, cancellationToken).ConfigureAwait(false);
diff --git a/Emby.Server.Implementations/Library/PathManager.cs b/Emby.Server.Implementations/Library/PathManager.cs
index c910abadb..a9b7a1274 100644
--- a/Emby.Server.Implementations/Library/PathManager.cs
+++ b/Emby.Server.Implementations/Library/PathManager.cs
@@ -1,5 +1,8 @@
+using System;
+using System.Collections.Generic;
using System.Globalization;
using System.IO;
+using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.IO;
@@ -12,25 +15,87 @@ namespace Emby.Server.Implementations.Library;
public class PathManager : IPathManager
{
private readonly IServerConfigurationManager _config;
+ private readonly IApplicationPaths _appPaths;
/// <summary>
/// Initializes a new instance of the <see cref="PathManager"/> class.
/// </summary>
/// <param name="config">The server configuration manager.</param>
+ /// <param name="appPaths">The application paths.</param>
public PathManager(
- IServerConfigurationManager config)
+ IServerConfigurationManager config,
+ IApplicationPaths appPaths)
{
_config = config;
+ _appPaths = appPaths;
+ }
+
+ private string SubtitleCachePath => Path.Combine(_appPaths.DataPath, "subtitles");
+
+ private string AttachmentCachePath => Path.Combine(_appPaths.DataPath, "attachments");
+
+ /// <inheritdoc />
+ public string GetAttachmentPath(string mediaSourceId, string fileName)
+ {
+ return Path.Combine(GetAttachmentFolderPath(mediaSourceId), fileName);
+ }
+
+ /// <inheritdoc />
+ public string GetAttachmentFolderPath(string mediaSourceId)
+ {
+ var id = Guid.Parse(mediaSourceId).ToString("D", CultureInfo.InvariantCulture).AsSpan();
+
+ return Path.Join(AttachmentCachePath, id[..2], id);
+ }
+
+ /// <inheritdoc />
+ public string GetSubtitleFolderPath(string mediaSourceId)
+ {
+ var id = Guid.Parse(mediaSourceId).ToString("D", CultureInfo.InvariantCulture).AsSpan();
+
+ return Path.Join(SubtitleCachePath, id[..2], id);
+ }
+
+ /// <inheritdoc />
+ public string GetSubtitlePath(string mediaSourceId, int streamIndex, string extension)
+ {
+ return Path.Combine(GetSubtitleFolderPath(mediaSourceId), streamIndex.ToString(CultureInfo.InvariantCulture) + extension);
}
/// <inheritdoc />
public string GetTrickplayDirectory(BaseItem item, bool saveWithMedia = false)
{
- var basePath = _config.ApplicationPaths.TrickplayPath;
- var idString = item.Id.ToString("N", CultureInfo.InvariantCulture);
+ var id = item.Id.ToString("D", CultureInfo.InvariantCulture).AsSpan();
return saveWithMedia
- ? Path.Combine(item.ContainingFolderPath, Path.ChangeExtension(item.Path, ".trickplay"))
- : Path.Combine(basePath, idString);
+ ? Path.Combine(item.ContainingFolderPath, Path.ChangeExtension(Path.GetFileName(item.Path), ".trickplay"))
+ : Path.Join(_config.ApplicationPaths.TrickplayPath, id[..2], id);
+ }
+
+ /// <inheritdoc/>
+ public string GetChapterImageFolderPath(BaseItem item)
+ {
+ return Path.Combine(item.GetInternalMetadataPath(), "chapters");
+ }
+
+ /// <inheritdoc/>
+ public string GetChapterImagePath(BaseItem item, long chapterPositionTicks)
+ {
+ var filename = item.DateModified.Ticks.ToString(CultureInfo.InvariantCulture) + "_" + chapterPositionTicks.ToString(CultureInfo.InvariantCulture) + ".jpg";
+
+ return Path.Combine(GetChapterImageFolderPath(item), filename);
+ }
+
+ /// <inheritdoc/>
+ public IReadOnlyList<string> GetExtractedDataPaths(BaseItem item)
+ {
+ var mediaSourceId = item.Id.ToString("N", CultureInfo.InvariantCulture);
+ return [
+ GetAttachmentFolderPath(mediaSourceId),
+ GetSubtitleFolderPath(mediaSourceId),
+ GetTrickplayDirectory(item, false),
+ GetTrickplayDirectory(item, true),
+ GetChapterImageFolderPath(item)
+ ];
}
}
diff --git a/Emby.Server.Implementations/Library/ResolverHelper.cs b/Emby.Server.Implementations/Library/ResolverHelper.cs
index c9e3a4daf..ab6bc4907 100644
--- a/Emby.Server.Implementations/Library/ResolverHelper.cs
+++ b/Emby.Server.Implementations/Library/ResolverHelper.cs
@@ -136,23 +136,33 @@ namespace Emby.Server.Implementations.Library
if (config.UseFileCreationTimeForDateAdded)
{
- // directoryService.getFile may return null
- if (info is not null)
+ var fileCreationDate = info?.CreationTimeUtc;
+ if (fileCreationDate is not null)
{
- var dateCreated = info.CreationTimeUtc;
-
+ var dateCreated = fileCreationDate;
if (dateCreated.Equals(DateTime.MinValue))
{
dateCreated = DateTime.UtcNow;
}
- item.DateCreated = dateCreated;
+ item.DateCreated = dateCreated.Value;
}
}
else
{
item.DateCreated = DateTime.UtcNow;
}
+
+ if (info is not null && !info.IsDirectory)
+ {
+ item.Size = info.Length;
+ }
+
+ var fileModificationDate = info?.LastWriteTimeUtc;
+ if (fileModificationDate.HasValue)
+ {
+ item.DateModified = fileModificationDate.Value;
+ }
}
}
}
diff --git a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs
index f1aeb1340..d78f8b991 100644
--- a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs
@@ -456,8 +456,9 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies
{
var videoPath = result.Items[0].Path;
var hasPhotos = photos.Any(i => !PhotoResolver.IsOwnedByResolvedMedia(videoPath, i.Name));
+ var hasOtherSubfolders = multiDiscFolders.Count > 0;
- if (!hasPhotos)
+ if (!hasPhotos && !hasOtherSubfolders)
{
var movie = (T)result.Items[0];
movie.IsInMixedFolder = false;
diff --git a/Emby.Server.Implementations/Library/SplashscreenPostScanTask.cs b/Emby.Server.Implementations/Library/SplashscreenPostScanTask.cs
index 0c9edd839..71ce3b601 100644
--- a/Emby.Server.Implementations/Library/SplashscreenPostScanTask.cs
+++ b/Emby.Server.Implementations/Library/SplashscreenPostScanTask.cs
@@ -11,7 +11,6 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Querying;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Library;
@@ -78,15 +77,15 @@ public class SplashscreenPostScanTask : ILibraryPostScanTask
CollapseBoxSetItems = false,
Recursive = true,
DtoOptions = new DtoOptions(false),
- ImageTypes = new[] { imageType },
+ ImageTypes = [imageType],
Limit = 30,
// TODO max parental rating configurable
- MaxParentalRating = 10,
- OrderBy = new[]
- {
+ MaxParentalRating = new(10, null),
+ OrderBy =
+ [
(ItemSortBy.Random, SortOrder.Ascending)
- },
- IncludeItemTypes = new[] { BaseItemKind.Movie, BaseItemKind.Series }
+ ],
+ IncludeItemTypes = [BaseItemKind.Movie, BaseItemKind.Series]
});
}
}
diff --git a/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs
index d51f9aaa7..a31d5ecca 100644
--- a/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs
+++ b/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs
@@ -5,45 +5,44 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.Library.Validators
+namespace Emby.Server.Implementations.Library.Validators;
+
+/// <summary>
+/// Class ArtistsPostScanTask.
+/// </summary>
+public class ArtistsPostScanTask : ILibraryPostScanTask
{
/// <summary>
- /// Class ArtistsPostScanTask.
+ /// The _library manager.
/// </summary>
- public class ArtistsPostScanTask : ILibraryPostScanTask
- {
- /// <summary>
- /// The _library manager.
- /// </summary>
- private readonly ILibraryManager _libraryManager;
- private readonly ILogger<ArtistsValidator> _logger;
- private readonly IItemRepository _itemRepo;
+ private readonly ILibraryManager _libraryManager;
+ private readonly ILogger<ArtistsValidator> _logger;
+ private readonly IItemRepository _itemRepo;
- /// <summary>
- /// Initializes a new instance of the <see cref="ArtistsPostScanTask" /> class.
- /// </summary>
- /// <param name="libraryManager">The library manager.</param>
- /// <param name="logger">The logger.</param>
- /// <param name="itemRepo">The item repository.</param>
- public ArtistsPostScanTask(
- ILibraryManager libraryManager,
- ILogger<ArtistsValidator> logger,
- IItemRepository itemRepo)
- {
- _libraryManager = libraryManager;
- _logger = logger;
- _itemRepo = itemRepo;
- }
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ArtistsPostScanTask" /> class.
+ /// </summary>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="itemRepo">The item repository.</param>
+ public ArtistsPostScanTask(
+ ILibraryManager libraryManager,
+ ILogger<ArtistsValidator> logger,
+ IItemRepository itemRepo)
+ {
+ _libraryManager = libraryManager;
+ _logger = logger;
+ _itemRepo = itemRepo;
+ }
- /// <summary>
- /// Runs the specified progress.
- /// </summary>
- /// <param name="progress">The progress.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- public Task Run(IProgress<double> progress, CancellationToken cancellationToken)
- {
- return new ArtistsValidator(_libraryManager, _logger, _itemRepo).Run(progress, cancellationToken);
- }
+ /// <summary>
+ /// Runs the specified progress.
+ /// </summary>
+ /// <param name="progress">The progress.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Task.</returns>
+ public Task Run(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ return new ArtistsValidator(_libraryManager, _logger, _itemRepo).Run(progress, cancellationToken);
}
}
diff --git a/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs b/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs
index 7591e8391..7cc851b73 100644
--- a/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs
@@ -10,102 +10,101 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.Library.Validators
+namespace Emby.Server.Implementations.Library.Validators;
+
+/// <summary>
+/// Class ArtistsValidator.
+/// </summary>
+public class ArtistsValidator
{
/// <summary>
- /// Class ArtistsValidator.
+ /// The library manager.
/// </summary>
- public class ArtistsValidator
- {
- /// <summary>
- /// The library manager.
- /// </summary>
- private readonly ILibraryManager _libraryManager;
+ private readonly ILibraryManager _libraryManager;
- /// <summary>
- /// The logger.
- /// </summary>
- private readonly ILogger<ArtistsValidator> _logger;
- private readonly IItemRepository _itemRepo;
+ /// <summary>
+ /// The logger.
+ /// </summary>
+ private readonly ILogger<ArtistsValidator> _logger;
+ private readonly IItemRepository _itemRepo;
- /// <summary>
- /// Initializes a new instance of the <see cref="ArtistsValidator" /> class.
- /// </summary>
- /// <param name="libraryManager">The library manager.</param>
- /// <param name="logger">The logger.</param>
- /// <param name="itemRepo">The item repository.</param>
- public ArtistsValidator(ILibraryManager libraryManager, ILogger<ArtistsValidator> logger, IItemRepository itemRepo)
- {
- _libraryManager = libraryManager;
- _logger = logger;
- _itemRepo = itemRepo;
- }
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ArtistsValidator" /> class.
+ /// </summary>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="itemRepo">The item repository.</param>
+ public ArtistsValidator(ILibraryManager libraryManager, ILogger<ArtistsValidator> logger, IItemRepository itemRepo)
+ {
+ _libraryManager = libraryManager;
+ _logger = logger;
+ _itemRepo = itemRepo;
+ }
- /// <summary>
- /// Runs the specified progress.
- /// </summary>
- /// <param name="progress">The progress.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
- {
- var names = _itemRepo.GetAllArtistNames();
+ /// <summary>
+ /// Runs the specified progress.
+ /// </summary>
+ /// <param name="progress">The progress.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Task.</returns>
+ public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ var names = _itemRepo.GetAllArtistNames();
- var numComplete = 0;
- var count = names.Count;
+ var numComplete = 0;
+ var count = names.Count;
- foreach (var name in names)
+ foreach (var name in names)
+ {
+ try
{
- try
- {
- var item = _libraryManager.GetArtist(name);
-
- await item.RefreshMetadata(cancellationToken).ConfigureAwait(false);
- }
- catch (OperationCanceledException)
- {
- // Don't clutter the log
- throw;
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error refreshing {ArtistName}", name);
- }
-
- numComplete++;
- double percent = numComplete;
- percent /= count;
- percent *= 100;
+ var item = _libraryManager.GetArtist(name);
- progress.Report(percent);
+ await item.RefreshMetadata(cancellationToken).ConfigureAwait(false);
}
-
- var deadEntities = _libraryManager.GetItemList(new InternalItemsQuery
+ catch (OperationCanceledException)
{
- IncludeItemTypes = new[] { BaseItemKind.MusicArtist },
- IsDeadArtist = true,
- IsLocked = false
- }).Cast<MusicArtist>().ToList();
-
- foreach (var item in deadEntities)
+ // Don't clutter the log
+ throw;
+ }
+ catch (Exception ex)
{
- if (!item.IsAccessedByName)
- {
- continue;
- }
+ _logger.LogError(ex, "Error refreshing {ArtistName}", name);
+ }
- _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N", CultureInfo.InvariantCulture), item.Name, item.GetType().Name);
+ numComplete++;
+ double percent = numComplete;
+ percent /= count;
+ percent *= 100;
- _libraryManager.DeleteItem(
- item,
- new DeleteOptions
- {
- DeleteFileLocation = false
- },
- false);
+ progress.Report(percent);
+ }
+
+ var deadEntities = _libraryManager.GetItemList(new InternalItemsQuery
+ {
+ IncludeItemTypes = [BaseItemKind.MusicArtist],
+ IsDeadArtist = true,
+ IsLocked = false
+ }).Cast<MusicArtist>().ToList();
+
+ foreach (var item in deadEntities)
+ {
+ if (!item.IsAccessedByName)
+ {
+ continue;
}
- progress.Report(100);
+ _logger.LogInformation("Deleting dead {ItemType} {ItemId} {ItemName}", item.GetType().Name, item.Id.ToString("N", CultureInfo.InvariantCulture), item.Name);
+
+ _libraryManager.DeleteItem(
+ item,
+ new DeleteOptions
+ {
+ DeleteFileLocation = false
+ },
+ false);
}
+
+ progress.Report(100);
}
}
diff --git a/Emby.Server.Implementations/Library/Validators/CollectionPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/CollectionPostScanTask.cs
index 337b1afdd..38631e0de 100644
--- a/Emby.Server.Implementations/Library/Validators/CollectionPostScanTask.cs
+++ b/Emby.Server.Implementations/Library/Validators/CollectionPostScanTask.cs
@@ -9,149 +9,146 @@ using MediaBrowser.Controller.Collections;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Querying;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.Library.Validators
+namespace Emby.Server.Implementations.Library.Validators;
+
+/// <summary>
+/// Class CollectionPostScanTask.
+/// </summary>
+public class CollectionPostScanTask : ILibraryPostScanTask
{
+ private readonly ILibraryManager _libraryManager;
+ private readonly ICollectionManager _collectionManager;
+ private readonly ILogger<CollectionPostScanTask> _logger;
+
/// <summary>
- /// Class CollectionPostScanTask.
+ /// Initializes a new instance of the <see cref="CollectionPostScanTask" /> class.
/// </summary>
- public class CollectionPostScanTask : ILibraryPostScanTask
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="collectionManager">The collection manager.</param>
+ /// <param name="logger">The logger.</param>
+ public CollectionPostScanTask(
+ ILibraryManager libraryManager,
+ ICollectionManager collectionManager,
+ ILogger<CollectionPostScanTask> logger)
{
- private readonly ILibraryManager _libraryManager;
- private readonly ICollectionManager _collectionManager;
- private readonly ILogger<CollectionPostScanTask> _logger;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CollectionPostScanTask" /> class.
- /// </summary>
- /// <param name="libraryManager">The library manager.</param>
- /// <param name="collectionManager">The collection manager.</param>
- /// <param name="logger">The logger.</param>
- public CollectionPostScanTask(
- ILibraryManager libraryManager,
- ICollectionManager collectionManager,
- ILogger<CollectionPostScanTask> logger)
- {
- _libraryManager = libraryManager;
- _collectionManager = collectionManager;
- _logger = logger;
- }
+ _libraryManager = libraryManager;
+ _collectionManager = collectionManager;
+ _logger = logger;
+ }
- /// <summary>
- /// Runs the specified progress.
- /// </summary>
- /// <param name="progress">The progress.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
- {
- var collectionNameMoviesMap = new Dictionary<string, HashSet<Guid>>();
+ /// <summary>
+ /// Runs the specified progress.
+ /// </summary>
+ /// <param name="progress">The progress.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Task.</returns>
+ public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ var collectionNameMoviesMap = new Dictionary<string, HashSet<Guid>>();
- foreach (var library in _libraryManager.RootFolder.Children)
+ foreach (var library in _libraryManager.RootFolder.Children)
+ {
+ if (!_libraryManager.GetLibraryOptions(library).AutomaticallyAddToCollection)
{
- if (!_libraryManager.GetLibraryOptions(library).AutomaticallyAddToCollection)
- {
- continue;
- }
+ continue;
+ }
- var startIndex = 0;
- var pagesize = 1000;
+ var startIndex = 0;
+ var pagesize = 1000;
- while (true)
+ while (true)
+ {
+ var movies = _libraryManager.GetItemList(new InternalItemsQuery
{
- var movies = _libraryManager.GetItemList(new InternalItemsQuery
- {
- MediaTypes = new[] { MediaType.Video },
- IncludeItemTypes = new[] { BaseItemKind.Movie },
- IsVirtualItem = false,
- OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) },
- Parent = library,
- StartIndex = startIndex,
- Limit = pagesize,
- Recursive = true
- });
-
- foreach (var m in movies)
+ MediaTypes = [MediaType.Video],
+ IncludeItemTypes = [BaseItemKind.Movie],
+ IsVirtualItem = false,
+ OrderBy = [(ItemSortBy.SortName, SortOrder.Ascending)],
+ Parent = library,
+ StartIndex = startIndex,
+ Limit = pagesize,
+ Recursive = true
+ });
+
+ foreach (var m in movies)
+ {
+ if (m is Movie movie && !string.IsNullOrEmpty(movie.CollectionName))
{
- if (m is Movie movie && !string.IsNullOrEmpty(movie.CollectionName))
+ if (collectionNameMoviesMap.TryGetValue(movie.CollectionName, out var movieList))
{
- if (collectionNameMoviesMap.TryGetValue(movie.CollectionName, out var movieList))
- {
- movieList.Add(movie.Id);
- }
- else
- {
- collectionNameMoviesMap[movie.CollectionName] = new HashSet<Guid> { movie.Id };
- }
+ movieList.Add(movie.Id);
+ }
+ else
+ {
+ collectionNameMoviesMap[movie.CollectionName] = new HashSet<Guid> { movie.Id };
}
}
+ }
- if (movies.Count < pagesize)
- {
- break;
- }
-
- startIndex += pagesize;
+ if (movies.Count < pagesize)
+ {
+ break;
}
+
+ startIndex += pagesize;
}
+ }
- var numComplete = 0;
- var count = collectionNameMoviesMap.Count;
+ var numComplete = 0;
+ var count = collectionNameMoviesMap.Count;
- if (count == 0)
- {
- progress.Report(100);
- return;
- }
+ if (count == 0)
+ {
+ progress.Report(100);
+ return;
+ }
- var boxSets = _libraryManager.GetItemList(new InternalItemsQuery
- {
- IncludeItemTypes = new[] { BaseItemKind.BoxSet },
- CollapseBoxSetItems = false,
- Recursive = true
- });
+ var boxSets = _libraryManager.GetItemList(new InternalItemsQuery
+ {
+ IncludeItemTypes = [BaseItemKind.BoxSet],
+ CollapseBoxSetItems = false,
+ Recursive = true
+ });
- foreach (var (collectionName, movieIds) in collectionNameMoviesMap)
+ foreach (var (collectionName, movieIds) in collectionNameMoviesMap)
+ {
+ try
{
- try
+ var boxSet = boxSets.FirstOrDefault(b => b?.Name == collectionName) as BoxSet;
+ if (boxSet is null)
{
- var boxSet = boxSets.FirstOrDefault(b => b?.Name == collectionName) as BoxSet;
- if (boxSet is null)
+ // won't automatically create collection if only one movie in it
+ if (movieIds.Count >= 2)
{
- // won't automatically create collection if only one movie in it
- if (movieIds.Count >= 2)
+ boxSet = await _collectionManager.CreateCollectionAsync(new CollectionCreationOptions
{
- boxSet = await _collectionManager.CreateCollectionAsync(new CollectionCreationOptions
- {
- Name = collectionName,
- IsLocked = true
- });
+ Name = collectionName,
+ IsLocked = true
+ }).ConfigureAwait(false);
- await _collectionManager.AddToCollectionAsync(boxSet.Id, movieIds);
- }
+ await _collectionManager.AddToCollectionAsync(boxSet.Id, movieIds).ConfigureAwait(false);
}
- else
- {
- await _collectionManager.AddToCollectionAsync(boxSet.Id, movieIds);
- }
-
- numComplete++;
- double percent = numComplete;
- percent /= count;
- percent *= 100;
-
- progress.Report(percent);
}
- catch (Exception ex)
+ else
{
- _logger.LogError(ex, "Error refreshing {CollectionName} with {@MovieIds}", collectionName, movieIds);
+ await _collectionManager.AddToCollectionAsync(boxSet.Id, movieIds).ConfigureAwait(false);
}
- }
- progress.Report(100);
+ numComplete++;
+ double percent = numComplete;
+ percent /= count;
+ percent *= 100;
+
+ progress.Report(percent);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error refreshing {CollectionName} with {@MovieIds}", collectionName, movieIds);
+ }
}
+
+ progress.Report(100);
}
}
diff --git a/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs
index d21d2887b..5097e0073 100644
--- a/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs
+++ b/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs
@@ -5,45 +5,44 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.Library.Validators
+namespace Emby.Server.Implementations.Library.Validators;
+
+/// <summary>
+/// Class GenresPostScanTask.
+/// </summary>
+public class GenresPostScanTask : ILibraryPostScanTask
{
/// <summary>
- /// Class GenresPostScanTask.
+ /// The _library manager.
/// </summary>
- public class GenresPostScanTask : ILibraryPostScanTask
- {
- /// <summary>
- /// The _library manager.
- /// </summary>
- private readonly ILibraryManager _libraryManager;
- private readonly ILogger<GenresValidator> _logger;
- private readonly IItemRepository _itemRepo;
+ private readonly ILibraryManager _libraryManager;
+ private readonly ILogger<GenresValidator> _logger;
+ private readonly IItemRepository _itemRepo;
- /// <summary>
- /// Initializes a new instance of the <see cref="GenresPostScanTask" /> class.
- /// </summary>
- /// <param name="libraryManager">The library manager.</param>
- /// <param name="logger">The logger.</param>
- /// <param name="itemRepo">The item repository.</param>
- public GenresPostScanTask(
- ILibraryManager libraryManager,
- ILogger<GenresValidator> logger,
- IItemRepository itemRepo)
- {
- _libraryManager = libraryManager;
- _logger = logger;
- _itemRepo = itemRepo;
- }
+ /// <summary>
+ /// Initializes a new instance of the <see cref="GenresPostScanTask" /> class.
+ /// </summary>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="itemRepo">The item repository.</param>
+ public GenresPostScanTask(
+ ILibraryManager libraryManager,
+ ILogger<GenresValidator> logger,
+ IItemRepository itemRepo)
+ {
+ _libraryManager = libraryManager;
+ _logger = logger;
+ _itemRepo = itemRepo;
+ }
- /// <summary>
- /// Runs the specified progress.
- /// </summary>
- /// <param name="progress">The progress.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- public Task Run(IProgress<double> progress, CancellationToken cancellationToken)
- {
- return new GenresValidator(_libraryManager, _logger, _itemRepo).Run(progress, cancellationToken);
- }
+ /// <summary>
+ /// Runs the specified progress.
+ /// </summary>
+ /// <param name="progress">The progress.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Task.</returns>
+ public Task Run(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ return new GenresValidator(_libraryManager, _logger, _itemRepo).Run(progress, cancellationToken);
}
}
diff --git a/Emby.Server.Implementations/Library/Validators/GenresValidator.cs b/Emby.Server.Implementations/Library/Validators/GenresValidator.cs
index e59c62e23..fbfc9f7d5 100644
--- a/Emby.Server.Implementations/Library/Validators/GenresValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/GenresValidator.cs
@@ -1,81 +1,103 @@
using System;
+using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.Library.Validators
+namespace Emby.Server.Implementations.Library.Validators;
+
+/// <summary>
+/// Class GenresValidator.
+/// </summary>
+public class GenresValidator
{
/// <summary>
- /// Class GenresValidator.
+ /// The library manager.
+ /// </summary>
+ private readonly ILibraryManager _libraryManager;
+ private readonly IItemRepository _itemRepo;
+
+ /// <summary>
+ /// The logger.
/// </summary>
- public class GenresValidator
+ private readonly ILogger<GenresValidator> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="GenresValidator"/> class.
+ /// </summary>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="itemRepo">The item repository.</param>
+ public GenresValidator(ILibraryManager libraryManager, ILogger<GenresValidator> logger, IItemRepository itemRepo)
{
- /// <summary>
- /// The library manager.
- /// </summary>
- private readonly ILibraryManager _libraryManager;
- private readonly IItemRepository _itemRepo;
+ _libraryManager = libraryManager;
+ _logger = logger;
+ _itemRepo = itemRepo;
+ }
- /// <summary>
- /// The logger.
- /// </summary>
- private readonly ILogger<GenresValidator> _logger;
+ /// <summary>
+ /// Runs the specified progress.
+ /// </summary>
+ /// <param name="progress">The progress.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Task.</returns>
+ public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ var names = _itemRepo.GetGenreNames();
- /// <summary>
- /// Initializes a new instance of the <see cref="GenresValidator"/> class.
- /// </summary>
- /// <param name="libraryManager">The library manager.</param>
- /// <param name="logger">The logger.</param>
- /// <param name="itemRepo">The item repository.</param>
- public GenresValidator(ILibraryManager libraryManager, ILogger<GenresValidator> logger, IItemRepository itemRepo)
- {
- _libraryManager = libraryManager;
- _logger = logger;
- _itemRepo = itemRepo;
- }
+ var numComplete = 0;
+ var count = names.Count;
- /// <summary>
- /// Runs the specified progress.
- /// </summary>
- /// <param name="progress">The progress.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
+ foreach (var name in names)
{
- var names = _itemRepo.GetGenreNames();
-
- var numComplete = 0;
- var count = names.Count;
+ try
+ {
+ var item = _libraryManager.GetGenre(name);
- foreach (var name in names)
+ await item.RefreshMetadata(cancellationToken).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
{
- try
- {
- var item = _libraryManager.GetGenre(name);
+ // Don't clutter the log
+ throw;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error refreshing {GenreName}", name);
+ }
- await item.RefreshMetadata(cancellationToken).ConfigureAwait(false);
- }
- catch (OperationCanceledException)
- {
- // Don't clutter the log
- throw;
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error refreshing {GenreName}", name);
- }
+ numComplete++;
+ double percent = numComplete;
+ percent /= count;
+ percent *= 100;
- numComplete++;
- double percent = numComplete;
- percent /= count;
- percent *= 100;
+ progress.Report(percent);
+ }
- progress.Report(percent);
- }
+ var deadEntities = _libraryManager.GetItemList(new InternalItemsQuery
+ {
+ IncludeItemTypes = [BaseItemKind.Genre, BaseItemKind.MusicGenre],
+ IsDeadGenre = true,
+ IsLocked = false
+ });
- progress.Report(100);
+ foreach (var item in deadEntities)
+ {
+ _logger.LogInformation("Deleting dead {ItemType} {ItemId} {ItemName}", item.GetType().Name, item.Id.ToString("N", CultureInfo.InvariantCulture), item.Name);
+
+ _libraryManager.DeleteItem(
+ item,
+ new DeleteOptions
+ {
+ DeleteFileLocation = false
+ },
+ false);
}
+
+ progress.Report(100);
}
}
diff --git a/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs
index be119866b..76658a81b 100644
--- a/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs
+++ b/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs
@@ -5,45 +5,44 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.Library.Validators
+namespace Emby.Server.Implementations.Library.Validators;
+
+/// <summary>
+/// Class MusicGenresPostScanTask.
+/// </summary>
+public class MusicGenresPostScanTask : ILibraryPostScanTask
{
/// <summary>
- /// Class MusicGenresPostScanTask.
+ /// The library manager.
/// </summary>
- public class MusicGenresPostScanTask : ILibraryPostScanTask
- {
- /// <summary>
- /// The library manager.
- /// </summary>
- private readonly ILibraryManager _libraryManager;
- private readonly ILogger<MusicGenresValidator> _logger;
- private readonly IItemRepository _itemRepo;
+ private readonly ILibraryManager _libraryManager;
+ private readonly ILogger<MusicGenresValidator> _logger;
+ private readonly IItemRepository _itemRepo;
- /// <summary>
- /// Initializes a new instance of the <see cref="MusicGenresPostScanTask" /> class.
- /// </summary>
- /// <param name="libraryManager">The library manager.</param>
- /// <param name="logger">The logger.</param>
- /// <param name="itemRepo">The item repository.</param>
- public MusicGenresPostScanTask(
- ILibraryManager libraryManager,
- ILogger<MusicGenresValidator> logger,
- IItemRepository itemRepo)
- {
- _libraryManager = libraryManager;
- _logger = logger;
- _itemRepo = itemRepo;
- }
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MusicGenresPostScanTask" /> class.
+ /// </summary>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="itemRepo">The item repository.</param>
+ public MusicGenresPostScanTask(
+ ILibraryManager libraryManager,
+ ILogger<MusicGenresValidator> logger,
+ IItemRepository itemRepo)
+ {
+ _libraryManager = libraryManager;
+ _logger = logger;
+ _itemRepo = itemRepo;
+ }
- /// <summary>
- /// Runs the specified progress.
- /// </summary>
- /// <param name="progress">The progress.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- public Task Run(IProgress<double> progress, CancellationToken cancellationToken)
- {
- return new MusicGenresValidator(_libraryManager, _logger, _itemRepo).Run(progress, cancellationToken);
- }
+ /// <summary>
+ /// Runs the specified progress.
+ /// </summary>
+ /// <param name="progress">The progress.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Task.</returns>
+ public Task Run(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ return new MusicGenresValidator(_libraryManager, _logger, _itemRepo).Run(progress, cancellationToken);
}
}
diff --git a/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs b/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs
index 1ecf4c87c..6203bce2b 100644
--- a/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs
@@ -5,77 +5,76 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.Library.Validators
+namespace Emby.Server.Implementations.Library.Validators;
+
+/// <summary>
+/// Class MusicGenresValidator.
+/// </summary>
+public class MusicGenresValidator
{
/// <summary>
- /// Class MusicGenresValidator.
+ /// The library manager.
/// </summary>
- public class MusicGenresValidator
- {
- /// <summary>
- /// The library manager.
- /// </summary>
- private readonly ILibraryManager _libraryManager;
+ private readonly ILibraryManager _libraryManager;
- /// <summary>
- /// The logger.
- /// </summary>
- private readonly ILogger<MusicGenresValidator> _logger;
- private readonly IItemRepository _itemRepo;
+ /// <summary>
+ /// The logger.
+ /// </summary>
+ private readonly ILogger<MusicGenresValidator> _logger;
+ private readonly IItemRepository _itemRepo;
- /// <summary>
- /// Initializes a new instance of the <see cref="MusicGenresValidator" /> class.
- /// </summary>
- /// <param name="libraryManager">The library manager.</param>
- /// <param name="logger">The logger.</param>
- /// <param name="itemRepo">The item repository.</param>
- public MusicGenresValidator(ILibraryManager libraryManager, ILogger<MusicGenresValidator> logger, IItemRepository itemRepo)
- {
- _libraryManager = libraryManager;
- _logger = logger;
- _itemRepo = itemRepo;
- }
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MusicGenresValidator" /> class.
+ /// </summary>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="itemRepo">The item repository.</param>
+ public MusicGenresValidator(ILibraryManager libraryManager, ILogger<MusicGenresValidator> logger, IItemRepository itemRepo)
+ {
+ _libraryManager = libraryManager;
+ _logger = logger;
+ _itemRepo = itemRepo;
+ }
- /// <summary>
- /// Runs the specified progress.
- /// </summary>
- /// <param name="progress">The progress.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
- {
- var names = _itemRepo.GetMusicGenreNames();
+ /// <summary>
+ /// Runs the specified progress.
+ /// </summary>
+ /// <param name="progress">The progress.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Task.</returns>
+ public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ var names = _itemRepo.GetMusicGenreNames();
- var numComplete = 0;
- var count = names.Count;
+ var numComplete = 0;
+ var count = names.Count;
- foreach (var name in names)
+ foreach (var name in names)
+ {
+ try
{
- try
- {
- var item = _libraryManager.GetMusicGenre(name);
+ var item = _libraryManager.GetMusicGenre(name);
- await item.RefreshMetadata(cancellationToken).ConfigureAwait(false);
- }
- catch (OperationCanceledException)
- {
- // Don't clutter the log
- throw;
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error refreshing {GenreName}", name);
- }
-
- numComplete++;
- double percent = numComplete;
- percent /= count;
- percent *= 100;
-
- progress.Report(percent);
+ await item.RefreshMetadata(cancellationToken).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ // Don't clutter the log
+ throw;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error refreshing {GenreName}", name);
}
- progress.Report(100);
+ numComplete++;
+ double percent = numComplete;
+ percent /= count;
+ percent *= 100;
+
+ progress.Report(percent);
}
+
+ progress.Report(100);
}
}
diff --git a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs
index 725b8f76c..b7fd24fa5 100644
--- a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs
@@ -9,119 +9,114 @@ using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.Library.Validators
+namespace Emby.Server.Implementations.Library.Validators;
+
+/// <summary>
+/// Class PeopleValidator.
+/// </summary>
+public class PeopleValidator
{
/// <summary>
- /// Class PeopleValidator.
+ /// The _library manager.
/// </summary>
- public class PeopleValidator
+ private readonly ILibraryManager _libraryManager;
+
+ /// <summary>
+ /// The _logger.
+ /// </summary>
+ private readonly ILogger _logger;
+
+ private readonly IFileSystem _fileSystem;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PeopleValidator" /> class.
+ /// </summary>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="fileSystem">The file system.</param>
+ public PeopleValidator(ILibraryManager libraryManager, ILogger logger, IFileSystem fileSystem)
{
- /// <summary>
- /// The _library manager.
- /// </summary>
- private readonly ILibraryManager _libraryManager;
-
- /// <summary>
- /// The _logger.
- /// </summary>
- private readonly ILogger _logger;
-
- private readonly IFileSystem _fileSystem;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="PeopleValidator" /> class.
- /// </summary>
- /// <param name="libraryManager">The library manager.</param>
- /// <param name="logger">The logger.</param>
- /// <param name="fileSystem">The file system.</param>
- public PeopleValidator(ILibraryManager libraryManager, ILogger logger, IFileSystem fileSystem)
- {
- _libraryManager = libraryManager;
- _logger = logger;
- _fileSystem = fileSystem;
- }
+ _libraryManager = libraryManager;
+ _logger = logger;
+ _fileSystem = fileSystem;
+ }
- /// <summary>
- /// Validates the people.
- /// </summary>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <param name="progress">The progress.</param>
- /// <returns>Task.</returns>
- public async Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
- {
- var people = _libraryManager.GetPeopleNames(new InternalPeopleQuery());
+ /// <summary>
+ /// Validates the people.
+ /// </summary>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <param name="progress">The progress.</param>
+ /// <returns>Task.</returns>
+ public async Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
+ {
+ var people = _libraryManager.GetPeopleNames(new InternalPeopleQuery());
- var numComplete = 0;
+ var numComplete = 0;
- var numPeople = people.Count;
+ var numPeople = people.Count;
- _logger.LogDebug("Will refresh {0} people", numPeople);
+ _logger.LogDebug("Will refresh {Amount} people", numPeople);
- foreach (var person in people)
- {
- cancellationToken.ThrowIfCancellationRequested();
+ foreach (var person in people)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
- try
- {
- var item = _libraryManager.GetPerson(person);
- if (item is null)
- {
- _logger.LogWarning("Failed to get person: {Name}", person);
- continue;
- }
-
- var options = new MetadataRefreshOptions(new DirectoryService(_fileSystem))
- {
- ImageRefreshMode = MetadataRefreshMode.ValidationOnly,
- MetadataRefreshMode = MetadataRefreshMode.ValidationOnly
- };
-
- await item.RefreshMetadata(options, cancellationToken).ConfigureAwait(false);
- }
- catch (OperationCanceledException)
- {
- throw;
- }
- catch (Exception ex)
+ try
+ {
+ var item = _libraryManager.GetPerson(person);
+ if (item is null)
{
- _logger.LogError(ex, "Error validating IBN entry {Person}", person);
+ _logger.LogWarning("Failed to get person: {Name}", person);
+ continue;
}
- // Update progress
- numComplete++;
- double percent = numComplete;
- percent /= numPeople;
+ var options = new MetadataRefreshOptions(new DirectoryService(_fileSystem))
+ {
+ ImageRefreshMode = MetadataRefreshMode.ValidationOnly,
+ MetadataRefreshMode = MetadataRefreshMode.ValidationOnly
+ };
- progress.Report(100 * percent);
+ await item.RefreshMetadata(options, cancellationToken).ConfigureAwait(false);
}
-
- var deadEntities = _libraryManager.GetItemList(new InternalItemsQuery
+ catch (OperationCanceledException)
{
- IncludeItemTypes = [BaseItemKind.Person],
- IsDeadPerson = true,
- IsLocked = false
- });
-
- foreach (var item in deadEntities)
+ throw;
+ }
+ catch (Exception ex)
{
- _logger.LogInformation(
- "Deleting dead {2} {0} {1}.",
- item.Id.ToString("N", CultureInfo.InvariantCulture),
- item.Name,
- item.GetType().Name);
-
- _libraryManager.DeleteItem(
- item,
- new DeleteOptions
- {
- DeleteFileLocation = false
- },
- false);
+ _logger.LogError(ex, "Error validating IBN entry {Person}", person);
}
- progress.Report(100);
+ // Update progress
+ numComplete++;
+ double percent = numComplete;
+ percent /= numPeople;
- _logger.LogInformation("People validation complete");
+ progress.Report(100 * percent);
}
+
+ var deadEntities = _libraryManager.GetItemList(new InternalItemsQuery
+ {
+ IncludeItemTypes = [BaseItemKind.Person],
+ IsDeadPerson = true,
+ IsLocked = false
+ });
+
+ foreach (var item in deadEntities)
+ {
+ _logger.LogInformation("Deleting dead {ItemType} {ItemId} {ItemName}", item.GetType().Name, item.Id.ToString("N", CultureInfo.InvariantCulture), item.Name);
+
+ _libraryManager.DeleteItem(
+ item,
+ new DeleteOptions
+ {
+ DeleteFileLocation = false
+ },
+ false);
+ }
+
+ progress.Report(100);
+
+ _logger.LogInformation("People validation complete");
}
}
diff --git a/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs
index c682b156b..67c56c104 100644
--- a/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs
+++ b/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs
@@ -5,46 +5,45 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.Library.Validators
+namespace Emby.Server.Implementations.Library.Validators;
+
+/// <summary>
+/// Class MusicGenresPostScanTask.
+/// </summary>
+public class StudiosPostScanTask : ILibraryPostScanTask
{
/// <summary>
- /// Class MusicGenresPostScanTask.
+ /// The _library manager.
/// </summary>
- public class StudiosPostScanTask : ILibraryPostScanTask
- {
- /// <summary>
- /// The _library manager.
- /// </summary>
- private readonly ILibraryManager _libraryManager;
+ private readonly ILibraryManager _libraryManager;
- private readonly ILogger<StudiosValidator> _logger;
- private readonly IItemRepository _itemRepo;
+ private readonly ILogger<StudiosValidator> _logger;
+ private readonly IItemRepository _itemRepo;
- /// <summary>
- /// Initializes a new instance of the <see cref="StudiosPostScanTask" /> class.
- /// </summary>
- /// <param name="libraryManager">The library manager.</param>
- /// <param name="logger">The logger.</param>
- /// <param name="itemRepo">The item repository.</param>
- public StudiosPostScanTask(
- ILibraryManager libraryManager,
- ILogger<StudiosValidator> logger,
- IItemRepository itemRepo)
- {
- _libraryManager = libraryManager;
- _logger = logger;
- _itemRepo = itemRepo;
- }
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StudiosPostScanTask" /> class.
+ /// </summary>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="itemRepo">The item repository.</param>
+ public StudiosPostScanTask(
+ ILibraryManager libraryManager,
+ ILogger<StudiosValidator> logger,
+ IItemRepository itemRepo)
+ {
+ _libraryManager = libraryManager;
+ _logger = logger;
+ _itemRepo = itemRepo;
+ }
- /// <summary>
- /// Runs the specified progress.
- /// </summary>
- /// <param name="progress">The progress.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- public Task Run(IProgress<double> progress, CancellationToken cancellationToken)
- {
- return new StudiosValidator(_libraryManager, _logger, _itemRepo).Run(progress, cancellationToken);
- }
+ /// <summary>
+ /// Runs the specified progress.
+ /// </summary>
+ /// <param name="progress">The progress.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Task.</returns>
+ public Task Run(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ return new StudiosValidator(_libraryManager, _logger, _itemRepo).Run(progress, cancellationToken);
}
}
diff --git a/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs b/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs
index 26bc49c1f..5b87e4d9d 100644
--- a/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs
@@ -8,98 +8,97 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.Library.Validators
+namespace Emby.Server.Implementations.Library.Validators;
+
+/// <summary>
+/// Class StudiosValidator.
+/// </summary>
+public class StudiosValidator
{
/// <summary>
- /// Class StudiosValidator.
+ /// The library manager.
/// </summary>
- public class StudiosValidator
- {
- /// <summary>
- /// The library manager.
- /// </summary>
- private readonly ILibraryManager _libraryManager;
+ private readonly ILibraryManager _libraryManager;
- private readonly IItemRepository _itemRepo;
+ private readonly IItemRepository _itemRepo;
- /// <summary>
- /// The logger.
- /// </summary>
- private readonly ILogger<StudiosValidator> _logger;
+ /// <summary>
+ /// The logger.
+ /// </summary>
+ private readonly ILogger<StudiosValidator> _logger;
- /// <summary>
- /// Initializes a new instance of the <see cref="StudiosValidator" /> class.
- /// </summary>
- /// <param name="libraryManager">The library manager.</param>
- /// <param name="logger">The logger.</param>
- /// <param name="itemRepo">The item repository.</param>
- public StudiosValidator(ILibraryManager libraryManager, ILogger<StudiosValidator> logger, IItemRepository itemRepo)
- {
- _libraryManager = libraryManager;
- _logger = logger;
- _itemRepo = itemRepo;
- }
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StudiosValidator" /> class.
+ /// </summary>
+ /// <param name="libraryManager">The library manager.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="itemRepo">The item repository.</param>
+ public StudiosValidator(ILibraryManager libraryManager, ILogger<StudiosValidator> logger, IItemRepository itemRepo)
+ {
+ _libraryManager = libraryManager;
+ _logger = logger;
+ _itemRepo = itemRepo;
+ }
- /// <summary>
- /// Runs the specified progress.
- /// </summary>
- /// <param name="progress">The progress.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
- {
- var names = _itemRepo.GetStudioNames();
+ /// <summary>
+ /// Runs the specified progress.
+ /// </summary>
+ /// <param name="progress">The progress.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Task.</returns>
+ public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ var names = _itemRepo.GetStudioNames();
- var numComplete = 0;
- var count = names.Count;
+ var numComplete = 0;
+ var count = names.Count;
- foreach (var name in names)
+ foreach (var name in names)
+ {
+ try
{
- try
- {
- var item = _libraryManager.GetStudio(name);
+ var item = _libraryManager.GetStudio(name);
- await item.RefreshMetadata(cancellationToken).ConfigureAwait(false);
- }
- catch (OperationCanceledException)
- {
- // Don't clutter the log
- throw;
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error refreshing {StudioName}", name);
- }
-
- numComplete++;
- double percent = numComplete;
- percent /= count;
- percent *= 100;
-
- progress.Report(percent);
+ await item.RefreshMetadata(cancellationToken).ConfigureAwait(false);
}
-
- var deadEntities = _libraryManager.GetItemList(new InternalItemsQuery
+ catch (OperationCanceledException)
{
- IncludeItemTypes = new[] { BaseItemKind.Studio },
- IsDeadStudio = true,
- IsLocked = false
- });
-
- foreach (var item in deadEntities)
+ // Don't clutter the log
+ throw;
+ }
+ catch (Exception ex)
{
- _logger.LogInformation("Deleting dead {ItemType} {ItemId} {ItemName}", item.GetType().Name, item.Id.ToString("N", CultureInfo.InvariantCulture), item.Name);
-
- _libraryManager.DeleteItem(
- item,
- new DeleteOptions
- {
- DeleteFileLocation = false
- },
- false);
+ _logger.LogError(ex, "Error refreshing {StudioName}", name);
}
- progress.Report(100);
+ numComplete++;
+ double percent = numComplete;
+ percent /= count;
+ percent *= 100;
+
+ progress.Report(percent);
}
+
+ var deadEntities = _libraryManager.GetItemList(new InternalItemsQuery
+ {
+ IncludeItemTypes = [BaseItemKind.Studio],
+ IsDeadStudio = true,
+ IsLocked = false
+ });
+
+ foreach (var item in deadEntities)
+ {
+ _logger.LogInformation("Deleting dead {ItemType} {ItemId} {ItemName}", item.GetType().Name, item.Id.ToString("N", CultureInfo.InvariantCulture), item.Name);
+
+ _libraryManager.DeleteItem(
+ item,
+ new DeleteOptions
+ {
+ DeleteFileLocation = false
+ },
+ false);
+ }
+
+ progress.Report(100);
}
}
diff --git a/Emby.Server.Implementations/Localization/Core/af.json b/Emby.Server.Implementations/Localization/Core/af.json
index e89ede10b..1dce58923 100644
--- a/Emby.Server.Implementations/Localization/Core/af.json
+++ b/Emby.Server.Implementations/Localization/Core/af.json
@@ -129,5 +129,11 @@
"TaskAudioNormalizationDescription": "Skandeer lêers vir oudio-normaliseringsdata.",
"TaskAudioNormalization": "Odio Normalisering",
"TaskCleanCollectionsAndPlaylists": "Maak versamelings en snitlyste skoon",
- "TaskCleanCollectionsAndPlaylistsDescription": "Verwyder items uit versamelings en snitlyste wat nie meer bestaan nie."
+ "TaskCleanCollectionsAndPlaylistsDescription": "Verwyder items uit versamelings en snitlyste wat nie meer bestaan nie.",
+ "TaskDownloadMissingLyrics": "Laai tekorte lirieke af",
+ "TaskDownloadMissingLyricsDescription": "Laai lirieke af vir liedjies",
+ "TaskExtractMediaSegments": "Media Segment Skandeer",
+ "TaskExtractMediaSegmentsDescription": "Onttrek of verkry mediasegmente van MediaSegment-geaktiveerde inproppe.",
+ "TaskMoveTrickplayImages": "Migreer Trickplay Beeldligging",
+ "TaskMoveTrickplayImagesDescription": "Skuif ontstaande trickplay lêers volgens die biblioteekinstellings."
}
diff --git a/Emby.Server.Implementations/Localization/Core/ar.json b/Emby.Server.Implementations/Localization/Core/ar.json
index 2d29eb5bf..0e1b9e0d8 100644
--- a/Emby.Server.Implementations/Localization/Core/ar.json
+++ b/Emby.Server.Implementations/Localization/Core/ar.json
@@ -125,8 +125,8 @@
"TaskKeyframeExtractor": "مستخرج الإطار الرئيسي",
"External": "خارجي",
"HearingImpaired": "ضعاف السمع",
- "TaskRefreshTrickplayImages": "توليد صور Trickplay",
- "TaskRefreshTrickplayImagesDescription": "يُنشئ معاينات Trickplay لمقاطع الفيديو في المكتبات المُمكّنة.",
+ "TaskRefreshTrickplayImages": "توليد صور المعاينة السريعة",
+ "TaskRefreshTrickplayImagesDescription": "يُولّد معاينات تنقل سريع لمقاطع الفيديو ضمن المكتبات المفعّلة.",
"TaskCleanCollectionsAndPlaylists": "حذف المجموعات وقوائم التشغيل",
"TaskCleanCollectionsAndPlaylistsDescription": "حذف عناصر من المجموعات وقوائم التشغيل التي لم تعد موجودة.",
"TaskAudioNormalization": "تسوية الصوت",
diff --git a/Emby.Server.Implementations/Localization/Core/de.json b/Emby.Server.Implementations/Localization/Core/de.json
index c38af5bf4..a411e27e1 100644
--- a/Emby.Server.Implementations/Localization/Core/de.json
+++ b/Emby.Server.Implementations/Localization/Core/de.json
@@ -43,7 +43,7 @@
"NameInstallFailed": "Installation von {0} fehlgeschlagen",
"NameSeasonNumber": "Staffel {0}",
"NameSeasonUnknown": "Staffel unbekannt",
- "NewVersionIsAvailable": "Eine neue Version von Jellyfin-Server steht zum Download bereit.",
+ "NewVersionIsAvailable": "Eine neue Jellyfin-Serverversion steht zum Download bereit.",
"NotificationOptionApplicationUpdateAvailable": "Anwendungsaktualisierung verfügbar",
"NotificationOptionApplicationUpdateInstalled": "Anwendungsaktualisierung installiert",
"NotificationOptionAudioPlayback": "Audiowiedergabe gestartet",
@@ -72,12 +72,12 @@
"ServerNameNeedsToBeRestarted": "{0} muss neu gestartet werden",
"Shows": "Serien",
"Songs": "Lieder",
- "StartupEmbyServerIsLoading": "Jellyfin-Server startet, bitte versuche es gleich noch einmal.",
+ "StartupEmbyServerIsLoading": "Jellyfin-Server lädt. Bitte versuche es gleich noch einmal.",
"SubtitleDownloadFailureForItem": "Download der Untertitel fehlgeschlagen für {0}",
"SubtitleDownloadFailureFromForItem": "Untertitel von {0} für {1} konnten nicht heruntergeladen werden",
"Sync": "Synchronisation",
"System": "System",
- "TvShows": "TV-Sendungen",
+ "TvShows": "Serien",
"User": "Benutzer",
"UserCreatedWithName": "Benutzer {0} wurde erstellt",
"UserDeletedWithName": "Benutzer {0} wurde gelöscht",
@@ -92,30 +92,30 @@
"ValueHasBeenAddedToLibrary": "{0} wurde deiner Bibliothek hinzugefügt",
"ValueSpecialEpisodeName": "Extra - {0}",
"VersionNumber": "Version {0}",
- "TaskDownloadMissingSubtitlesDescription": "Suche im Internet basierend auf den Metadaten-Einstellungen nach fehlenden Untertiteln.",
- "TaskDownloadMissingSubtitles": "Lade fehlende Untertitel herunter",
- "TaskRefreshChannelsDescription": "Aktualisiere Internet-Kanal-Informationen.",
- "TaskRefreshChannels": "Aktualisiere Kanäle",
- "TaskCleanTranscodeDescription": "Löscht Transkodierdateien, die älter als einen Tag sind.",
- "TaskCleanTranscode": "Räume Transkodierungs-Verzeichnis auf",
+ "TaskDownloadMissingSubtitlesDescription": "Sucht im Internet basierend auf den Metadaten-Einstellungen nach fehlenden Untertiteln.",
+ "TaskDownloadMissingSubtitles": "Fehlende Untertitel herunterladen",
+ "TaskRefreshChannelsDescription": "Aktualisiert Internet-Kanal-Informationen.",
+ "TaskRefreshChannels": "Kanäle aktualisieren",
+ "TaskCleanTranscodeDescription": "Löscht Transkodierungsdateien, die älter als einen Tag sind.",
+ "TaskCleanTranscode": "Transkodierungs-Verzeichnis aufräumen",
"TaskUpdatePluginsDescription": "Lädt Updates für Plugins herunter, welche für automatische Updates konfiguriert sind und installiert diese.",
- "TaskUpdatePlugins": "Aktualisiere Plugins",
+ "TaskUpdatePlugins": "Plugins aktualisieren",
"TaskRefreshPeopleDescription": "Aktualisiert Metadaten für Schauspieler und Regisseure in deinen Bibliotheken.",
- "TaskRefreshPeople": "Aktualisiere Personen",
+ "TaskRefreshPeople": "Personen aktualisieren",
"TaskCleanLogsDescription": "Lösche Log-Dateien, die älter als {0} Tage sind.",
- "TaskCleanLogs": "Räumt Log-Verzeichnis auf",
- "TaskRefreshLibraryDescription": "Scannt alle Bibliotheken nach neu hinzugefügten Dateien und aktualisiere Metadaten.",
- "TaskRefreshLibrary": "Scanne Medien-Bibliothek",
+ "TaskCleanLogs": "Log-Verzeichnis aufräumen",
+ "TaskRefreshLibraryDescription": "Durchsucht alle Bibliotheken nach neu hinzugefügten Dateien und aktualisiert Metadaten.",
+ "TaskRefreshLibrary": "Medien-Bibliothek scannen",
"TaskRefreshChapterImagesDescription": "Erstellt Vorschaubilder für Videos, die Kapitel besitzen.",
- "TaskRefreshChapterImages": "Extrahiere Kapitel-Bilder",
- "TaskCleanCacheDescription": "Löscht nicht mehr benötigte Zwischenspeicherdateien.",
- "TaskCleanCache": "Leere Zwischenspeicher",
+ "TaskRefreshChapterImages": "Kapitel-Bilder extrahieren",
+ "TaskCleanCacheDescription": "Löscht vom System nicht mehr benötigte Zwischenspeicherdateien.",
+ "TaskCleanCache": "Zwischenspeicher-Verzeichnis aufräumen",
"TasksChannelsCategory": "Internet-Kanäle",
"TasksApplicationCategory": "Anwendung",
"TasksLibraryCategory": "Bibliothek",
"TasksMaintenanceCategory": "Wartung",
"TaskCleanActivityLogDescription": "Löscht Aktivitätsprotokolleinträge, die älter als das konfigurierte Alter sind.",
- "TaskCleanActivityLog": "Aktivitätsprotokoll aufräumen",
+ "TaskCleanActivityLog": "Aktivitätsprotokolle aufräumen",
"Undefined": "Undefiniert",
"Forced": "Erzwungen",
"Default": "Standard",
@@ -128,12 +128,12 @@
"TaskRefreshTrickplayImages": "Trickplay-Bilder generieren",
"TaskRefreshTrickplayImagesDescription": "Erstellt ein Trickplay-Vorschauen für Videos in aktivierten Bibliotheken.",
"TaskCleanCollectionsAndPlaylists": "Sammlungen und Playlisten aufräumen",
- "TaskCleanCollectionsAndPlaylistsDescription": "Lösche nicht mehr vorhandene Einträge aus den Sammlungen und Playlisten.",
+ "TaskCleanCollectionsAndPlaylistsDescription": "Löscht nicht mehr vorhandene Einträge aus den Sammlungen und Playlisten.",
"TaskAudioNormalization": "Audio Normalisierung",
"TaskAudioNormalizationDescription": "Durchsucht Dateien nach Audionormalisierungsdaten.",
"TaskDownloadMissingLyricsDescription": "Lädt Songtexte herunter",
"TaskDownloadMissingLyrics": "Fehlende Songtexte herunterladen",
- "TaskExtractMediaSegments": "Scanne Mediensegmente",
+ "TaskExtractMediaSegments": "Mediensegmente scannen",
"TaskExtractMediaSegmentsDescription": "Extrahiert oder empfängt Mediensegmente von Plugins die Mediensegmente nutzen.",
"TaskMoveTrickplayImages": "Verzeichnis für Trickplay-Bilder migrieren",
"TaskMoveTrickplayImagesDescription": "Trickplay-Bilder werden entsprechend der Bibliothekseinstellungen verschoben."
diff --git a/Emby.Server.Implementations/Localization/Core/gl.json b/Emby.Server.Implementations/Localization/Core/gl.json
index 3ba3e6679..55b309098 100644
--- a/Emby.Server.Implementations/Localization/Core/gl.json
+++ b/Emby.Server.Implementations/Localization/Core/gl.json
@@ -123,5 +123,17 @@
"TaskKeyframeExtractorDescription": "Extrae fragmentos do vídeo para crear listas de reprodución HLS máis precisas. Podería levarlle bastante tempo.",
"External": "Externo",
"HearingImpaired": "Problemas de audición",
- "TaskKeyframeExtractor": "Extractor de fragmentos"
+ "TaskKeyframeExtractor": "Extractor de fragmentos",
+ "TaskAudioNormalization": "Normalización do audio",
+ "TaskRefreshTrickplayImagesDescription": "Crea vistas previas de reprodución con truco para vídeos en bibliotecas activadas.",
+ "TaskDownloadMissingLyrics": "Descargar letras que faltan",
+ "TaskDownloadMissingLyricsDescription": "Descargas de letras das cancións",
+ "TaskCleanCollectionsAndPlaylists": "Limpar coleccións e listas de reprodución",
+ "TaskCleanCollectionsAndPlaylistsDescription": "Elimina elementos de coleccións e listas de reprodución que xa non existen.",
+ "TaskExtractMediaSegmentsDescription": "Extrae ou obtén segmentos multimedia de complementos habilitados para o Segmento de medios.",
+ "TaskExtractMediaSegments": "Escaneo de segmentos multimedia",
+ "TaskMoveTrickplayImages": "Migrar a localización da imaxe de Trickplay",
+ "TaskMoveTrickplayImagesDescription": "Move os ficheiros de reprodución con trickplay existentes segundo a configuración da biblioteca.",
+ "TaskRefreshTrickplayImages": "Xerar imaxes de Trickplay",
+ "TaskAudioNormalizationDescription": "Analiza ficheiros para obter datos de normalización de audio."
}
diff --git a/Emby.Server.Implementations/Localization/Core/he.json b/Emby.Server.Implementations/Localization/Core/he.json
index 34d5cf050..1809c9d3f 100644
--- a/Emby.Server.Implementations/Localization/Core/he.json
+++ b/Emby.Server.Implementations/Localization/Core/he.json
@@ -125,16 +125,16 @@
"TaskKeyframeExtractor": "מחלץ תמונות מפתח",
"External": "חיצוני",
"HearingImpaired": "לקוי שמיעה",
- "TaskRefreshTrickplayImages": "יצירת תמונות המחשה",
- "TaskRefreshTrickplayImagesDescription": "יוצר תמונות המחשה לסרטונים שפעילים בספריות.",
+ "TaskRefreshTrickplayImages": "יצירת תמונות Trickplay",
+ "TaskRefreshTrickplayImagesDescription": "יוצר תמונות Trickplay לסרטונים בספריות הפעילות.",
"TaskAudioNormalization": "נרמול שמע",
"TaskCleanCollectionsAndPlaylistsDescription": "מנקה פריטים לא קיימים מאוספים ורשימות השמעה.",
"TaskAudioNormalizationDescription": "מחפש קבצי נורמליזציה של שמע.",
"TaskCleanCollectionsAndPlaylists": "מנקה אוספים ורשימות השמעה",
"TaskDownloadMissingLyrics": "הורדת מילים חסרות",
"TaskDownloadMissingLyricsDescription": "הורדת מילים לשירים",
- "TaskMoveTrickplayImages": "העברת מיקום התמונות",
+ "TaskMoveTrickplayImages": "העברת מיקום של תמונות Trickplay",
"TaskExtractMediaSegments": "סריקת מדיה",
"TaskExtractMediaSegmentsDescription": "מחלץ חלקי מדיה מתוספים המאפשרים זאת.",
- "TaskMoveTrickplayImagesDescription": "הזזת קבצי טריקפליי קיימים בהתאם להגדרות הספרייה."
+ "TaskMoveTrickplayImagesDescription": "הזזת קבצי Trickplay קיימים בהתאם להגדרות הספרייה."
}
diff --git a/Emby.Server.Implementations/Localization/Core/he_IL.json b/Emby.Server.Implementations/Localization/Core/he_IL.json
new file mode 100644
index 000000000..0967ef424
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/he_IL.json
@@ -0,0 +1 @@
+{}
diff --git a/Emby.Server.Implementations/Localization/Core/lzh.json b/Emby.Server.Implementations/Localization/Core/lzh.json
index 031a4dac7..9fb53e41d 100644
--- a/Emby.Server.Implementations/Localization/Core/lzh.json
+++ b/Emby.Server.Implementations/Localization/Core/lzh.json
@@ -2,5 +2,10 @@
"Albums": "辑册",
"Artists": "艺人",
"AuthenticationSucceededWithUserName": "{0} 授之权矣",
- "Books": "册"
+ "Books": "册",
+ "Genres": "类",
+ "HeaderAlbumArtists": "辑者",
+ "Favorites": "至爱",
+ "Folders": "箧",
+ "HeaderContinueWatching": "接目未竟"
}
diff --git a/Emby.Server.Implementations/Localization/Core/mr.json b/Emby.Server.Implementations/Localization/Core/mr.json
index 13c58e0ab..5a99d8c53 100644
--- a/Emby.Server.Implementations/Localization/Core/mr.json
+++ b/Emby.Server.Implementations/Localization/Core/mr.json
@@ -118,12 +118,17 @@
"MessageNamedServerConfigurationUpdatedWithValue": "सर्व्हर कॉन्फिगरेशन विभाग {0} अद्यतनित केला गेला आहे",
"Inherit": "वारसा",
"Forced": "सक्ती केली आहे",
- "FailedLoginAttemptWithUserName": "अयशस्वी लॉगिन {0} पासून प्रयत्न करा",
+ "FailedLoginAttemptWithUserName": "{0} कडून लॉगिन करण्याचा प्रयत्न अयशस्वी झाला",
"External": "बाहेरचा",
"DeviceOnlineWithName": "{0} कनेक्ट झाले",
"DeviceOfflineWithName": "{0} डिस्कनेक्ट झाला आहे",
"AuthenticationSucceededWithUserName": "{0} यशस्वीरित्या प्रमाणीकृत",
"HearingImpaired": "कर्णबधीर",
"TaskRefreshTrickplayImages": "ट्रिकप्ले प्रतिमा तयार करा",
- "TaskRefreshTrickplayImagesDescription": "सक्षम लायब्ररीमधील व्हिडिओंसाठी ट्रिकप्ले पूर्वावलोकन तयार करते."
+ "TaskRefreshTrickplayImagesDescription": "सक्षम लायब्ररीमधील व्हिडिओंसाठी ट्रिकप्ले पूर्वावलोकन तयार करते.",
+ "TaskCleanCollectionsAndPlaylists": "संग्रह आणि प्लेलिस्ट व्यवस्थित करा",
+ "TaskExtractMediaSegments": "मिडिया विभाग तपासणी",
+ "TaskMoveTrickplayImages": "ट्रिकप्ले प्रतिमेचे स्थान स्थलांतर करा",
+ "TaskDownloadMissingLyrics": "उपलब्ध नसलेली गीतपट्टी (Lyrics) डाउनलोड करा",
+ "TaskAudioNormalization": "ऑडिओ सामान्यीकरण"
}
diff --git a/Emby.Server.Implementations/Localization/Core/ms.json b/Emby.Server.Implementations/Localization/Core/ms.json
index c64bcda04..a3fc7881e 100644
--- a/Emby.Server.Implementations/Localization/Core/ms.json
+++ b/Emby.Server.Implementations/Localization/Core/ms.json
@@ -9,14 +9,14 @@
"Channels": "Saluran",
"ChapterNameValue": "Bab {0}",
"Collections": "Koleksi",
- "DeviceOfflineWithName": "{0} telah diputuskan sambungan",
+ "DeviceOfflineWithName": "{0} telah dinyahsambung",
"DeviceOnlineWithName": "{0} telah disambung",
- "FailedLoginAttemptWithUserName": "Percubaan log masuk daripada {0} gagal",
+ "FailedLoginAttemptWithUserName": "Percubaan gagal log masuk daripada {0}",
"Favorites": "Kegemaran",
- "Folders": "Fail-fail",
+ "Folders": "Folder-folder",
"Genres": "Genre-genre",
- "HeaderAlbumArtists": "Album Artis-artis",
- "HeaderContinueWatching": "Terus Menonton",
+ "HeaderAlbumArtists": "Album artis-artis",
+ "HeaderContinueWatching": "Teruskan Menonton",
"HeaderFavoriteAlbums": "Album-album Kegemaran",
"HeaderFavoriteArtists": "Artis-artis Kegemaran",
"HeaderFavoriteEpisodes": "Episod-episod Kegemaran",
@@ -25,26 +25,26 @@
"HeaderLiveTV": "TV Siaran Langsung",
"HeaderNextUp": "Seterusnya",
"HeaderRecordingGroups": "Kumpulan-kumpulan Rakaman",
- "HomeVideos": "Video Personal",
- "Inherit": "Mewarisi",
- "ItemAddedWithName": "{0} telah ditambahkan ke dalam pustaka",
+ "HomeVideos": "Video Peribadi",
+ "Inherit": "Warisi",
+ "ItemAddedWithName": "{0} telah ditambah ke dalam pustaka",
"ItemRemovedWithName": "{0} telah dibuang daripada pustaka",
"LabelIpAddressValue": "Alamat IP: {0}",
"LabelRunningTimeValue": "Masa berjalan: {0}",
- "Latest": "Terbaru",
- "MessageApplicationUpdated": "Jellyfin Server telah dikemas kini",
- "MessageApplicationUpdatedTo": "Jellyfin Server telah dikemas kini ke {0}",
- "MessageNamedServerConfigurationUpdatedWithValue": "Konfigurasi pelayan di bahagian {0} telah dikemas kini",
+ "Latest": "Terbaharu",
+ "MessageApplicationUpdated": "Pelayan Jellyfin telah dikemas kini",
+ "MessageApplicationUpdatedTo": "Pelayan Jellyfin telah dikemas kini ke {0}",
+ "MessageNamedServerConfigurationUpdatedWithValue": "Konfigurasi pelayan bahagian {0} telah dikemas kini",
"MessageServerConfigurationUpdated": "Konfigurasi pelayan telah dikemas kini",
"MixedContent": "Kandungan campuran",
"Movies": "Filem-filem",
"Music": "Muzik",
"MusicVideos": "Video Muzik",
"NameInstallFailed": "{0} pemasangan gagal",
- "NameSeasonNumber": "Musim {0}",
+ "NameSeasonNumber": "Musim ke-{0}",
"NameSeasonUnknown": "Musim Tidak Diketahui",
- "NewVersionIsAvailable": "Versi terbaru Jellyfin Server bersedia untuk dimuat turunkan.",
- "NotificationOptionApplicationUpdateAvailable": "Kemas kini aplikasi telah sedia",
+ "NewVersionIsAvailable": "Versi terbaharu Pelayan Jellyfin telah tersedia untuk dimuat turun.",
+ "NotificationOptionApplicationUpdateAvailable": "Kemas kini aplikasi telah tersedia",
"NotificationOptionApplicationUpdateInstalled": "Kemas kini aplikasi telah dipasang",
"NotificationOptionAudioPlayback": "Ulangmain audio bermula",
"NotificationOptionAudioPlaybackStopped": "Ulangmain audio dihentikan",
@@ -98,8 +98,8 @@
"TasksLibraryCategory": "Perpustakaan",
"TasksMaintenanceCategory": "Penyelenggaraan",
"Undefined": "Tidak ditentukan",
- "Forced": "Paksa",
- "Default": "Asal",
+ "Forced": "Dipaksa",
+ "Default": "Lalai",
"TaskCleanCache": "Bersihkan Direktori Cache",
"TaskCleanActivityLogDescription": "Padamkan entri log aktiviti yang lebih tua daripada usia yang dikonfigurasi.",
"TaskRefreshPeople": "Segarkan Orang",
diff --git a/Emby.Server.Implementations/Localization/Core/nb.json b/Emby.Server.Implementations/Localization/Core/nb.json
index b1b6e96ea..c00eb467f 100644
--- a/Emby.Server.Implementations/Localization/Core/nb.json
+++ b/Emby.Server.Implementations/Localization/Core/nb.json
@@ -1,6 +1,6 @@
{
"Albums": "Album",
- "AppDeviceValues": "App:{0}, Enhet: {1}",
+ "AppDeviceValues": "App: {0}, Enhet: {1}",
"Application": "Program",
"Artists": "Artister",
"AuthenticationSucceededWithUserName": "{0} har logget inn",
@@ -30,7 +30,7 @@
"ItemAddedWithName": "{0} ble lagt til i biblioteket",
"ItemRemovedWithName": "{0} ble fjernet fra biblioteket",
"LabelIpAddressValue": "IP-adresse: {0}",
- "LabelRunningTimeValue": "Spilletid {0}",
+ "LabelRunningTimeValue": "Spilletid: {0}",
"Latest": "Siste",
"MessageApplicationUpdated": "Jellyfin-serveren har blitt oppdatert",
"MessageApplicationUpdatedTo": "Jellyfin-serveren ble oppdatert til {0}",
diff --git a/Emby.Server.Implementations/Localization/Core/pt-PT.json b/Emby.Server.Implementations/Localization/Core/pt-PT.json
index 42ea5e0a4..6c49481c3 100644
--- a/Emby.Server.Implementations/Localization/Core/pt-PT.json
+++ b/Emby.Server.Implementations/Localization/Core/pt-PT.json
@@ -61,7 +61,7 @@
"NotificationOptionVideoPlayback": "Reprodução do vídeo iniciada",
"NotificationOptionVideoPlaybackStopped": "Reprodução do vídeo parada",
"Photos": "Fotografias",
- "Playlists": "Listas de Reprodução",
+ "Playlists": "Playlists",
"Plugin": "Extensão",
"PluginInstalledWithName": "{0} foi instalado",
"PluginUninstalledWithName": "{0} foi desinstalado",
@@ -77,7 +77,7 @@
"SubtitleDownloadFailureFromForItem": "Falha na transferência de legendas a partir de {0} para {1}",
"Sync": "Sincronização",
"System": "Sistema",
- "TvShows": "Programas TV",
+ "TvShows": "Séries",
"User": "Utilizador",
"UserCreatedWithName": "Utilizador {0} criado",
"UserDeletedWithName": "Utilizador {0} apagado",
@@ -118,7 +118,7 @@
"TaskCleanActivityLog": "Limpar registo de atividade",
"Undefined": "Indefinido",
"Forced": "Forçado",
- "Default": "Padrão",
+ "Default": "Predefinição",
"TaskOptimizeDatabaseDescription": "Otimiza e liberta espaço livre na base de dados. A execução desta tarefa depois de analisar a mediateca ou efetuar outras alterações que impliquem modificações na base de dados pode melhorar o desempenho.",
"TaskOptimizeDatabase": "Otimizar base de dados",
"TaskKeyframeExtractorDescription": "Extrai quadros-chave de ficheiros de video para criar listas de reprodução HLS mais precisas. Esta tarefa pode demorar algum tempo.",
diff --git a/Emby.Server.Implementations/Localization/Core/pt.json b/Emby.Server.Implementations/Localization/Core/pt.json
index 0bf0491be..52427f24b 100644
--- a/Emby.Server.Implementations/Localization/Core/pt.json
+++ b/Emby.Server.Implementations/Localization/Core/pt.json
@@ -76,11 +76,11 @@
"Inherit": "Herdar",
"HomeVideos": "Vídeos Caseiros",
"HeaderRecordingGroups": "Grupos de Gravação",
- "ValueSpecialEpisodeName": "Episódio Especial - {0}",
+ "ValueSpecialEpisodeName": "Especial - {0}",
"Sync": "Sincronização",
"Songs": "Músicas",
"Shows": "Séries",
- "Playlists": "Listas de Reprodução",
+ "Playlists": "Playlists",
"Photos": "Fotografias",
"Movies": "Filmes",
"FailedLoginAttemptWithUserName": "Tentativa de início de sessão falhada a partir de {0}",
diff --git a/Emby.Server.Implementations/Localization/Core/sq.json b/Emby.Server.Implementations/Localization/Core/sq.json
index 91ed11042..263459289 100644
--- a/Emby.Server.Implementations/Localization/Core/sq.json
+++ b/Emby.Server.Implementations/Localization/Core/sq.json
@@ -125,5 +125,15 @@
"External": "Jashtem",
"HearingImpaired": "Dëgjimi i dëmtuar",
"TaskRefreshTrickplayImages": "Krijo Imazhe Trickplay",
- "TaskRefreshTrickplayImagesDescription": "Krijon pamje paraprake për video në bibliotekat e aktivizuara."
+ "TaskRefreshTrickplayImagesDescription": "Krijon pamje paraprake për video në bibliotekat e aktivizuara.",
+ "TaskExtractMediaSegments": "Skanim i segmenteve të medias",
+ "TaskExtractMediaSegmentsDescription": "Nxjerr ose merr segmente mediaje nga shtojcat që kanë të aktivizuar MediaSegment.",
+ "TaskMoveTrickplayImages": "Migron vendndodhjen e imazheve Trickplay",
+ "TaskMoveTrickplayImagesDescription": "Zhvendos skedarët ekzistues të trickplay sipas cilësimeve të bibliotekës.",
+ "TaskDownloadMissingLyrics": "Shkarko tekstet e këngëve që mungojnë",
+ "TaskDownloadMissingLyricsDescription": "Shkarkon tekstet e këngëve",
+ "TaskCleanCollectionsAndPlaylists": "Pastron koleksionet dhe listat e këngëve",
+ "TaskCleanCollectionsAndPlaylistsDescription": "Heq elementet nga koleksionet dhe listat e këngëve që nuk ekzistojnë më.",
+ "TaskAudioNormalization": "Normalizimi i audios",
+ "TaskAudioNormalizationDescription": "Skannon skedarët për të dhëna të normalizimit të audios."
}
diff --git a/Emby.Server.Implementations/Localization/Core/ta.json b/Emby.Server.Implementations/Localization/Core/ta.json
index 7270d70fc..8de4e7115 100644
--- a/Emby.Server.Implementations/Localization/Core/ta.json
+++ b/Emby.Server.Implementations/Localization/Core/ta.json
@@ -129,5 +129,9 @@
"TaskCleanCollectionsAndPlaylists": "சேகரிப்புகள் மற்றும் பிளேலிஸ்ட்களை சுத்தம் செய்யவும்",
"TaskCleanCollectionsAndPlaylistsDescription": "சேகரிப்புகள் மற்றும் பிளேலிஸ்ட்களில் இருந்து உருப்படிகளை நீக்குகிறது.",
"TaskAudioNormalization": "ஆடியோ இயல்பாக்கம்",
- "TaskAudioNormalizationDescription": "ஆடியோ இயல்பாக்குதல் தரவுக்காக கோப்புகளை ஸ்கேன் செய்கிறது."
+ "TaskAudioNormalizationDescription": "ஆடியோ இயல்பாக்குதல் தரவுக்காக கோப்புகளை ஸ்கேன் செய்கிறது.",
+ "TaskDownloadMissingLyrics": "விடுபட்ட பாடல் வரிகளைப் பதிவிறக்கவும்",
+ "TaskDownloadMissingLyricsDescription": "பாடல்களுக்கான வரிகளைப் பதிவிறக்குகிறது",
+ "TaskMoveTrickplayImages": "ட்ரிக்பிளே பட இருப்பிடத்தை நகர்த்து",
+ "TaskMoveTrickplayImagesDescription": "நூலக அமைப்புகளுக்கு ஏற்ப ஏற்கனவே உள்ள ட்ரிக்பிளே கோப்புகளை நகர்த்துகிறது."
}
diff --git a/Emby.Server.Implementations/Localization/Core/te.json b/Emby.Server.Implementations/Localization/Core/te.json
index 7d4422d62..1fa2a3cc5 100644
--- a/Emby.Server.Implementations/Localization/Core/te.json
+++ b/Emby.Server.Implementations/Localization/Core/te.json
@@ -51,5 +51,13 @@
"Latest": "తాజా",
"NameInstallFailed": "{0} ఇన్‌స్టాలేషన్ విఫలమైంది",
"NameSeasonUnknown": "భాగం తెలియదు",
- "NotificationOptionApplicationUpdateAvailable": "అప్లికేషన్ అప్‌డేట్ అందుబాటులో ఉంది"
+ "NotificationOptionApplicationUpdateAvailable": "అప్లికేషన్ అప్‌డేట్ అందుబాటులో ఉంది",
+ "NameSeasonNumber": "సీజన్ {0}",
+ "NotificationOptionAudioPlaybackStopped": "ఆడియో ఆడటం ఆగిపోయింది",
+ "NotificationOptionNewLibraryContent": "కొత్త కంటెంట్ జోడించబడింది",
+ "MixedContent": "వివిధ రకాల కంటెంట్",
+ "NotificationOptionAudioPlayback": "ఆడియో ప్లే కావడం మొదలైంది",
+ "NotificationOptionCameraImageUploaded": "కెమెరా చిత్రాన్ని అప్లోడ్ చేశారు",
+ "NotificationOptionInstallationFailed": "ఇన్స్టాలేషన్ విఫలమైంది",
+ "NotificationOptionServerRestartRequired": "సర్వర్ రీస్టార్ట్ అవసరం"
}
diff --git a/Emby.Server.Implementations/Localization/Core/th.json b/Emby.Server.Implementations/Localization/Core/th.json
index da32e9776..407d95798 100644
--- a/Emby.Server.Implementations/Localization/Core/th.json
+++ b/Emby.Server.Implementations/Localization/Core/th.json
@@ -125,5 +125,12 @@
"TaskKeyframeExtractor": "ตัวแยกคีย์เฟรม",
"TaskKeyframeExtractorDescription": "แยกคีย์เฟรมจากไฟล์วีดีโอเพื่อสร้างรายการ HLS ให้ถูกต้อง. กระบวนการนี้อาจใช้ระยะเวลานาน",
"TaskRefreshTrickplayImages": "สร้างไฟล์รูปภาพสำหรับ Trickplay",
- "TaskRefreshTrickplayImagesDescription": "สร้างภาพตัวอย่างของวีดีโอในคลังที่เปิดใช้งาน Trickplay"
+ "TaskRefreshTrickplayImagesDescription": "สร้างภาพตัวอย่างของวีดีโอในคลังที่เปิดใช้งาน Trickplay",
+ "TaskDownloadMissingLyrics": "ดาวน์โหลดเนื้อเพลงที่หายไป",
+ "TaskDownloadMissingLyricsDescription": "ดาวน์โหลดเนื้อเพลงสำหรับเพลง",
+ "TaskAudioNormalization": "ปรับระดับเสียงให้สม่ำเสมอ",
+ "TaskAudioNormalizationDescription": "สแกนไฟล์เพื่อค้นหาข้อมูลการปรับระดับเสียงให้สม่ำเสมอ",
+ "TaskCleanCollectionsAndPlaylists": "จัดระเบียบคอลเลกชันและเพลย์ลิสต์",
+ "TaskCleanCollectionsAndPlaylistsDescription": "ลบรายการออกจากคอลเลกชันและเพลย์ลิสต์ที่ไม่มีแล้ว",
+ "TaskExtractMediaSegments": "การสแกนส่วนของสื่อมีเดีย"
}
diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs
index 754a01329..242f2af56 100644
--- a/Emby.Server.Implementations/Localization/LocalizationManager.cs
+++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs
@@ -1,7 +1,8 @@
using System;
using System.Collections.Concurrent;
+using System.Collections.Frozen;
using System.Collections.Generic;
-using System.Globalization;
+using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
@@ -26,20 +27,20 @@ namespace Emby.Server.Implementations.Localization
private const string CulturesPath = "Emby.Server.Implementations.Localization.iso6392.txt";
private const string CountriesPath = "Emby.Server.Implementations.Localization.countries.json";
private static readonly Assembly _assembly = typeof(LocalizationManager).Assembly;
- private static readonly string[] _unratedValues = { "n/a", "unrated", "not rated", "nr" };
+ private static readonly string[] _unratedValues = ["n/a", "unrated", "not rated", "nr"];
private readonly IServerConfigurationManager _configurationManager;
private readonly ILogger<LocalizationManager> _logger;
- private readonly Dictionary<string, Dictionary<string, ParentalRating>> _allParentalRatings =
- new Dictionary<string, Dictionary<string, ParentalRating>>(StringComparer.OrdinalIgnoreCase);
+ private readonly Dictionary<string, Dictionary<string, ParentalRatingScore?>> _allParentalRatings = new(StringComparer.OrdinalIgnoreCase);
- private readonly ConcurrentDictionary<string, Dictionary<string, string>> _dictionaries =
- new ConcurrentDictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
+ private readonly ConcurrentDictionary<string, Dictionary<string, string>> _dictionaries = new(StringComparer.OrdinalIgnoreCase);
private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
- private List<CultureDto> _cultures = new List<CultureDto>();
+ private List<CultureDto> _cultures = [];
+
+ private FrozenDictionary<string, string> _iso6392BtoT = null!;
/// <summary>
/// Initializes a new instance of the <see cref="LocalizationManager" /> class.
@@ -68,35 +69,26 @@ namespace Emby.Server.Implementations.Localization
continue;
}
- string countryCode = resource.Substring(RatingsPath.Length, 2);
- var dict = new Dictionary<string, ParentalRating>(StringComparer.OrdinalIgnoreCase);
-
- var stream = _assembly.GetManifestResourceStream(resource);
- await using (stream!.ConfigureAwait(false)) // shouldn't be null here, we just got the resource path from Assembly.GetManifestResourceNames()
+ using var stream = _assembly.GetManifestResourceStream(resource);
+ if (stream is not null)
{
- using var reader = new StreamReader(stream!);
- await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false))
+ var ratingSystem = await JsonSerializer.DeserializeAsync<ParentalRatingSystem>(stream, _jsonOptions).ConfigureAwait(false)
+ ?? throw new InvalidOperationException($"Invalid resource path: '{CountriesPath}'");
+
+ var dict = new Dictionary<string, ParentalRatingScore?>();
+ if (ratingSystem.Ratings is not null)
{
- if (string.IsNullOrWhiteSpace(line))
+ foreach (var ratingEntry in ratingSystem.Ratings)
{
- continue;
+ foreach (var ratingString in ratingEntry.RatingStrings)
+ {
+ dict[ratingString] = ratingEntry.RatingScore;
+ }
}
- string[] parts = line.Split(',');
- if (parts.Length == 2
- && int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
- {
- var name = parts[0];
- dict.Add(name, new ParentalRating(name, value));
- }
- else
- {
- _logger.LogWarning("Malformed line in ratings file for country {CountryCode}", countryCode);
- }
+ _allParentalRatings[ratingSystem.CountryCode] = dict;
}
}
-
- _allParentalRatings[countryCode] = dict;
}
await LoadCultures().ConfigureAwait(false);
@@ -111,22 +103,30 @@ namespace Emby.Server.Implementations.Localization
private async Task LoadCultures()
{
- List<CultureDto> list = new List<CultureDto>();
+ List<CultureDto> list = [];
+ Dictionary<string, string> iso6392BtoTdict = new Dictionary<string, string>();
- await using var stream = _assembly.GetManifestResourceStream(CulturesPath)
- ?? throw new InvalidOperationException($"Invalid resource path: '{CulturesPath}'");
- using var reader = new StreamReader(stream);
- await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false))
+ using var stream = _assembly.GetManifestResourceStream(CulturesPath);
+ if (stream is null)
{
- if (string.IsNullOrWhiteSpace(line))
+ throw new InvalidOperationException($"Invalid resource path: '{CulturesPath}'");
+ }
+ else
+ {
+ using var reader = new StreamReader(stream);
+ await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false))
{
- continue;
- }
+ if (string.IsNullOrWhiteSpace(line))
+ {
+ continue;
+ }
- var parts = line.Split('|');
+ var parts = line.Split('|');
+ if (parts.Length != 5)
+ {
+ throw new InvalidDataException($"Invalid culture data found at: '{line}'");
+ }
- if (parts.Length == 5)
- {
string name = parts[3];
if (string.IsNullOrWhiteSpace(name))
{
@@ -139,21 +139,26 @@ namespace Emby.Server.Implementations.Localization
continue;
}
- string[] threeletterNames;
+ string[] threeLetterNames;
if (string.IsNullOrWhiteSpace(parts[1]))
{
- threeletterNames = new[] { parts[0] };
+ threeLetterNames = [parts[0]];
}
else
{
- threeletterNames = new[] { parts[0], parts[1] };
+ threeLetterNames = [parts[0], parts[1]];
+
+ // In cases where there are two TLN the first one is ISO 639-2/T and the second one is ISO 639-2/B
+ // We need ISO 639-2/T for the .NET cultures so we cultivate a dictionary for the translation B->T
+ iso6392BtoTdict.TryAdd(parts[1], parts[0]);
}
- list.Add(new CultureDto(name, name, twoCharName, threeletterNames));
+ list.Add(new CultureDto(name, name, twoCharName, threeLetterNames));
}
- }
- _cultures = list;
+ _cultures = list;
+ _iso6392BtoT = iso6392BtoTdict.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
+ }
}
/// <inheritdoc />
@@ -176,82 +181,80 @@ namespace Emby.Server.Implementations.Localization
}
/// <inheritdoc />
- public IEnumerable<CountryInfo> GetCountries()
+ public IReadOnlyList<CountryInfo> GetCountries()
{
- using StreamReader reader = new StreamReader(
- _assembly.GetManifestResourceStream(CountriesPath) ?? throw new InvalidOperationException($"Invalid resource path: '{CountriesPath}'"));
- return JsonSerializer.Deserialize<IEnumerable<CountryInfo>>(reader.ReadToEnd(), _jsonOptions)
- ?? throw new InvalidOperationException($"Resource contains invalid data: '{CountriesPath}'");
+ using var stream = _assembly.GetManifestResourceStream(CountriesPath) ?? throw new InvalidOperationException($"Invalid resource path: '{CountriesPath}'");
+
+ return JsonSerializer.Deserialize<IReadOnlyList<CountryInfo>>(stream, _jsonOptions) ?? [];
}
/// <inheritdoc />
- public IEnumerable<ParentalRating> GetParentalRatings()
+ public IReadOnlyList<ParentalRating> GetParentalRatings()
{
// Use server default language for ratings
// Fall back to empty list if there are no parental ratings for that language
- var ratings = GetParentalRatingsDictionary()?.Values.ToList()
- ?? new List<ParentalRating>();
+ var ratings = GetParentalRatingsDictionary()?.Select(x => new ParentalRating(x.Key, x.Value)).ToList() ?? [];
// Add common ratings to ensure them being available for selection
// Based on the US rating system due to it being the main source of rating in the metadata providers
// Unrated
- if (!ratings.Any(x => x.Value is null))
+ if (!ratings.Any(x => x is null))
{
- ratings.Add(new ParentalRating("Unrated", null));
+ ratings.Add(new("Unrated", null));
}
// Minimum rating possible
- if (ratings.All(x => x.Value != 0))
+ if (ratings.All(x => x.RatingScore?.Score != 0))
{
- ratings.Add(new ParentalRating("Approved", 0));
+ ratings.Add(new("Approved", new(0, null)));
}
// Matches PG (this has different age restrictions depending on country)
- if (ratings.All(x => x.Value != 10))
+ if (ratings.All(x => x.RatingScore?.Score != 10))
{
- ratings.Add(new ParentalRating("10", 10));
+ ratings.Add(new("10", new(10, null)));
}
// Matches PG-13
- if (ratings.All(x => x.Value != 13))
+ if (ratings.All(x => x.RatingScore?.Score != 13))
{
- ratings.Add(new ParentalRating("13", 13));
+ ratings.Add(new("13", new(13, null)));
}
// Matches TV-14
- if (ratings.All(x => x.Value != 14))
+ if (ratings.All(x => x.RatingScore?.Score != 14))
{
- ratings.Add(new ParentalRating("14", 14));
+ ratings.Add(new("14", new(14, null)));
}
// Catchall if max rating of country is less than 21
// Using 21 instead of 18 to be sure to allow access to all rated content except adult and banned
- if (!ratings.Any(x => x.Value >= 21))
+ if (!ratings.Any(x => x.RatingScore?.Score >= 21))
{
- ratings.Add(new ParentalRating("21", 21));
+ ratings.Add(new ParentalRating("21", new(21, null)));
}
// A lot of countries don't explicitly have a separate rating for adult content
- if (ratings.All(x => x.Value != 1000))
+ if (ratings.All(x => x.RatingScore?.Score != 1000))
{
- ratings.Add(new ParentalRating("XXX", 1000));
+ ratings.Add(new ParentalRating("XXX", new(1000, null)));
}
// A lot of countries don't explicitly have a separate rating for banned content
- if (ratings.All(x => x.Value != 1001))
+ if (ratings.All(x => x.RatingScore?.Score != 1001))
{
- ratings.Add(new ParentalRating("Banned", 1001));
+ ratings.Add(new ParentalRating("Banned", new(1001, null)));
}
- return ratings.OrderBy(r => r.Value);
+ return [.. ratings.OrderBy(r => r.RatingScore?.Score).ThenBy(r => r.RatingScore?.SubScore)];
}
/// <summary>
/// Gets the parental ratings dictionary.
/// </summary>
/// <param name="countryCode">The optional two letter ISO language string.</param>
- /// <returns><see cref="Dictionary{String, ParentalRating}" />.</returns>
- private Dictionary<string, ParentalRating>? GetParentalRatingsDictionary(string? countryCode = null)
+ /// <returns><see cref="Dictionary{String, ParentalRatingScore}" />.</returns>
+ private Dictionary<string, ParentalRatingScore?>? GetParentalRatingsDictionary(string? countryCode = null)
{
// Fallback to server default if no country code is specified.
if (string.IsNullOrEmpty(countryCode))
@@ -268,7 +271,7 @@ namespace Emby.Server.Implementations.Localization
}
/// <inheritdoc />
- public int? GetRatingLevel(string rating, string? countryCode = null)
+ public ParentalRatingScore? GetRatingScore(string rating, string? countryCode = null)
{
ArgumentException.ThrowIfNullOrEmpty(rating);
@@ -278,11 +281,11 @@ namespace Emby.Server.Implementations.Localization
return null;
}
- // Convert integers directly
+ // Convert ints directly
// This may override some of the locale specific age ratings (but those always map to the same age)
if (int.TryParse(rating, out var ratingAge))
{
- return ratingAge;
+ return new(ratingAge, null);
}
// Fairly common for some users to have "Rated R" in their rating field
@@ -295,9 +298,9 @@ namespace Emby.Server.Implementations.Localization
if (!string.IsNullOrEmpty(countryCode))
{
var ratingsDictionary = GetParentalRatingsDictionary(countryCode);
- if (ratingsDictionary is not null && ratingsDictionary.TryGetValue(rating, out ParentalRating? value))
+ if (ratingsDictionary is not null && ratingsDictionary.TryGetValue(rating, out ParentalRatingScore? value))
{
- return value.Value;
+ return value;
}
}
else
@@ -305,9 +308,9 @@ namespace Emby.Server.Implementations.Localization
// Fall back to server default language for ratings check
// If it has no ratings, use the US ratings
var ratingsDictionary = GetParentalRatingsDictionary() ?? GetParentalRatingsDictionary("us");
- if (ratingsDictionary is not null && ratingsDictionary.TryGetValue(rating, out ParentalRating? value))
+ if (ratingsDictionary is not null && ratingsDictionary.TryGetValue(rating, out ParentalRatingScore? value))
{
- return value.Value;
+ return value;
}
}
@@ -316,7 +319,7 @@ namespace Emby.Server.Implementations.Localization
{
if (dictionary.TryGetValue(rating, out var value))
{
- return value.Value;
+ return value;
}
}
@@ -326,7 +329,7 @@ namespace Emby.Server.Implementations.Localization
var ratingLevelRightPart = rating.AsSpan().RightPart(':');
if (ratingLevelRightPart.Length != 0)
{
- return GetRatingLevel(ratingLevelRightPart.ToString());
+ return GetRatingScore(ratingLevelRightPart.ToString());
}
}
@@ -342,7 +345,7 @@ namespace Emby.Server.Implementations.Localization
if (ratingLevelRightPart.Length != 0)
{
// Check rating system of culture
- return GetRatingLevel(ratingLevelRightPart.ToString(), culture?.TwoLetterISOLanguageName);
+ return GetRatingScore(ratingLevelRightPart.ToString(), culture?.TwoLetterISOLanguageName);
}
}
@@ -406,7 +409,7 @@ namespace Emby.Server.Implementations.Localization
private async Task CopyInto(IDictionary<string, string> dictionary, string resourcePath)
{
- await using var stream = _assembly.GetManifestResourceStream(resourcePath);
+ using var stream = _assembly.GetManifestResourceStream(resourcePath);
// If a Culture doesn't have a translation the stream will be null and it defaults to en-us further up the chain
if (stream is null)
{
@@ -414,12 +417,7 @@ namespace Emby.Server.Implementations.Localization
return;
}
- var dict = await JsonSerializer.DeserializeAsync<Dictionary<string, string>>(stream, _jsonOptions).ConfigureAwait(false);
- if (dict is null)
- {
- throw new InvalidOperationException($"Resource contains invalid data: '{stream}'");
- }
-
+ var dict = await JsonSerializer.DeserializeAsync<Dictionary<string, string>>(stream, _jsonOptions).ConfigureAwait(false) ?? throw new InvalidOperationException($"Resource contains invalid data: '{stream}'");
foreach (var key in dict.Keys)
{
dictionary[key] = dict[key];
@@ -517,5 +515,26 @@ namespace Emby.Server.Implementations.Localization
yield return new LocalizationOption("漢語 (繁體字)", "zh-TW");
yield return new LocalizationOption("廣東話 (香港)", "zh-HK");
}
+
+ /// <inheritdoc />
+ public bool TryGetISO6392TFromB(string isoB, [NotNullWhen(true)] out string? isoT)
+ {
+ // Unlikely case the dictionary is not (yet) initialized properly
+ if (_iso6392BtoT is null)
+ {
+ isoT = null;
+ return false;
+ }
+
+ var result = _iso6392BtoT.TryGetValue(isoB, out isoT) && !string.IsNullOrEmpty(isoT);
+
+ // Ensure the ISO code being null if the result is false
+ if (!result)
+ {
+ isoT = null;
+ }
+
+ return result;
+ }
}
}
diff --git a/Emby.Server.Implementations/Localization/Ratings/0-prefer.csv b/Emby.Server.Implementations/Localization/Ratings/0-prefer.csv
deleted file mode 100644
index 36886ba76..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/0-prefer.csv
+++ /dev/null
@@ -1,11 +0,0 @@
-E,0
-EC,0
-T,7
-M,18
-AO,18
-UR,18
-RP,18
-X,1000
-XX,1000
-XXX,1000
-XXXX,1000
diff --git a/Emby.Server.Implementations/Localization/Ratings/0-prefer.json b/Emby.Server.Implementations/Localization/Ratings/0-prefer.json
new file mode 100644
index 000000000..b39015161
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/0-prefer.json
@@ -0,0 +1,34 @@
+{
+ "countryCode": "0-prefer",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["E", "EC"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["T"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["M", "AO", "UR", "RP"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["X", "XX", "XXX", "XXXX"],
+ "ratingScore": {
+ "score": 1000,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/ar.json b/Emby.Server.Implementations/Localization/Ratings/ar.json
new file mode 100644
index 000000000..73dfd2c7c
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/ar.json
@@ -0,0 +1,41 @@
+{
+ "countryCode": "ar",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["ATP"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["+13"],
+ "ratingScore": {
+ "score": 13,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["+16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["+18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["C"],
+ "ratingScore": {
+ "score": 1001,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/au.csv b/Emby.Server.Implementations/Localization/Ratings/au.csv
deleted file mode 100644
index 6e12759a4..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/au.csv
+++ /dev/null
@@ -1,17 +0,0 @@
-Exempt,0
-G,0
-7+,7
-PG,15
-M,15
-MA,15
-MA15+,15
-MA 15+,15
-16+,16
-R,18
-R18+,18
-R 18+,18
-18+,18
-X18+,1000
-X 18+,1000
-X,1000
-RC,1001
diff --git a/Emby.Server.Implementations/Localization/Ratings/au.json b/Emby.Server.Implementations/Localization/Ratings/au.json
new file mode 100644
index 000000000..a563df899
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/au.json
@@ -0,0 +1,69 @@
+{
+ "countryCode": "au",
+ "supportsSubScores": true,
+ "ratings": [
+ {
+ "ratingStrings": ["Exempt", "G"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["7+"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["PG"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["M"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": 2
+ }
+ },
+ {
+ "ratingStrings": ["MA", "MA 15+", "MA15+"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": 3
+ }
+ },
+ {
+ "ratingStrings": ["16+"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["18+", "R", "R18+", "R 18+"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["X", "X18", "X 18"],
+ "ratingScore": {
+ "score": 1000,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["RC"],
+ "ratingScore": {
+ "score": 1001,
+ "subScore": 0
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/be.csv b/Emby.Server.Implementations/Localization/Ratings/be.csv
deleted file mode 100644
index d171a7132..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/be.csv
+++ /dev/null
@@ -1,11 +0,0 @@
-AL,0
-KT,0
-TOUS,0
-MG6,6
-6,6
-9,9
-KNT,12
-12,12
-14,14
-16,16
-18,18
diff --git a/Emby.Server.Implementations/Localization/Ratings/be.json b/Emby.Server.Implementations/Localization/Ratings/be.json
new file mode 100644
index 000000000..18ea2c260
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/be.json
@@ -0,0 +1,55 @@
+{
+ "countryCode": "be",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["AL", "KT", "TOUS"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["6", "MG6"],
+ "ratingScore": {
+ "score": 6,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["9"],
+ "ratingScore": {
+ "score": 9,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12", "KNT"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["14"],
+ "ratingScore": {
+ "score": 14,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/bg.json b/Emby.Server.Implementations/Localization/Ratings/bg.json
new file mode 100644
index 000000000..fa03fa9df
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/bg.json
@@ -0,0 +1,34 @@
+{
+ "countryCode": "bg",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["A","B"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["C"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["D"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["X"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/br.csv b/Emby.Server.Implementations/Localization/Ratings/br.csv
deleted file mode 100644
index f6053c88c..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/br.csv
+++ /dev/null
@@ -1,14 +0,0 @@
-Livre,0
-L,0
-AL,0
-ER,10
-10,10
-A10,10
-12,12
-A12,12
-14,14
-A14,14
-16,16
-A16,16
-18,18
-A18,18
diff --git a/Emby.Server.Implementations/Localization/Ratings/br.json b/Emby.Server.Implementations/Localization/Ratings/br.json
new file mode 100644
index 000000000..f455b6643
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/br.json
@@ -0,0 +1,55 @@
+{
+ "countryCode": "br",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["L", "AL", "Livre"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["9"],
+ "ratingScore": {
+ "score": 9,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["10", "A10", "ER"],
+ "ratingScore": {
+ "score": 10,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12", "A12"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["14", "A14"],
+ "ratingScore": {
+ "score": 14,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["16", "A16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18", "A18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/ca.csv b/Emby.Server.Implementations/Localization/Ratings/ca.csv
deleted file mode 100644
index 41dbda134..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/ca.csv
+++ /dev/null
@@ -1,18 +0,0 @@
-E,0
-G,0
-TV-Y,0
-TV-G,0
-TV-Y7,7
-TV-Y7-FV,7
-PG,9
-TV-PG,9
-TV-14,14
-14A,14
-16+,16
-NC-17,17
-R,18
-TV-MA,18
-18A,18
-18+,18
-A,1000
-Prohibited,1001
diff --git a/Emby.Server.Implementations/Localization/Ratings/ca.json b/Emby.Server.Implementations/Localization/Ratings/ca.json
new file mode 100644
index 000000000..fa43a8f2b
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/ca.json
@@ -0,0 +1,90 @@
+{
+ "countryCode": "ca",
+ "supportsSubScores": true,
+ "ratings": [
+ {
+ "ratingStrings": ["E", "G", "TV-Y", "TV-G"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["TV-Y7"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["TV-Y7-FV"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["PG", "TV-PG"],
+ "ratingScore": {
+ "score": 9,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["14A"],
+ "ratingScore": {
+ "score": 14,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["TV-14"],
+ "ratingScore": {
+ "score": 14,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["16+"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["NC-17"],
+ "ratingScore": {
+ "score": 17,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["18A"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["18+", "TV-MA", "R"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["A"],
+ "ratingScore": {
+ "score": 1000,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["Prohibited"],
+ "ratingScore": {
+ "score": 1001,
+ "subScore": 0
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/cl.json b/Emby.Server.Implementations/Localization/Ratings/cl.json
new file mode 100644
index 000000000..086619471
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/cl.json
@@ -0,0 +1,41 @@
+{
+ "countryCode": "cl",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["TE"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["6"],
+ "ratingScore": {
+ "score": 6,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["TE+7"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["14"],
+ "ratingScore": {
+ "score": 14,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18", "18V", "18S"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/co.csv b/Emby.Server.Implementations/Localization/Ratings/co.csv
deleted file mode 100644
index e1e96c590..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/co.csv
+++ /dev/null
@@ -1,7 +0,0 @@
-T,0
-7,7
-12,12
-15,15
-18,18
-X,1000
-Prohibited,1001
diff --git a/Emby.Server.Implementations/Localization/Ratings/co.json b/Emby.Server.Implementations/Localization/Ratings/co.json
new file mode 100644
index 000000000..4eff6dcc5
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/co.json
@@ -0,0 +1,55 @@
+{
+ "countryCode": "co",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["T"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["7"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["15"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["X"],
+ "ratingScore": {
+ "score": 1000,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["Prohibited"],
+ "ratingScore": {
+ "score": 1001,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/cz.json b/Emby.Server.Implementations/Localization/Ratings/cz.json
new file mode 100644
index 000000000..92fff61a2
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/cz.json
@@ -0,0 +1,34 @@
+{
+ "countryCode": "cz",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["U"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12+"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["15+"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18+"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/de.csv b/Emby.Server.Implementations/Localization/Ratings/de.csv
deleted file mode 100644
index f6181575e..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/de.csv
+++ /dev/null
@@ -1,17 +0,0 @@
-Educational,0
-Infoprogramm,0
-FSK-0,0
-FSK 0,0
-0,0
-FSK-6,6
-FSK 6,6
-6,6
-FSK-12,12
-FSK 12,12
-12,12
-FSK-16,16
-FSK 16,16
-16,16
-FSK-18,18
-FSK 18,18
-18,18
diff --git a/Emby.Server.Implementations/Localization/Ratings/de.json b/Emby.Server.Implementations/Localization/Ratings/de.json
new file mode 100644
index 000000000..30c34b230
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/de.json
@@ -0,0 +1,41 @@
+{
+ "countryCode": "de",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["0", "FSK 0", "FSK-0", "Educational", "Infoprogramm"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["6", "FSK 6", "FSK-6"],
+ "ratingScore": {
+ "score": 6,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12", "FSK 12", "FSK-12"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["16", "FSK 16", "FSK-16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18", "FSK 18", "FSK-18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/dk.csv b/Emby.Server.Implementations/Localization/Ratings/dk.csv
deleted file mode 100644
index 4ef63b2ea..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/dk.csv
+++ /dev/null
@@ -1,7 +0,0 @@
-F,0
-A,0
-7,7
-11,11
-12,12
-15,15
-16,16
diff --git a/Emby.Server.Implementations/Localization/Ratings/dk.json b/Emby.Server.Implementations/Localization/Ratings/dk.json
new file mode 100644
index 000000000..9fcd6d44f
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/dk.json
@@ -0,0 +1,48 @@
+{
+ "countryCode": "dk",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["F", "A"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["7"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["11"],
+ "ratingScore": {
+ "score": 11,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["15"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/es.csv b/Emby.Server.Implementations/Localization/Ratings/es.csv
deleted file mode 100644
index ee5866090..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/es.csv
+++ /dev/null
@@ -1,25 +0,0 @@
-A,0
-A/fig,0
-A/i,0
-A/i/fig,0
-APTA,0
-ERI,0
-TP,0
-0+,0
-6+,6
-7/fig,7
-7/i,7
-7/i/fig,7
-7,7
-9+,9
-10,10
-12,12
-12/fig,12
-13,13
-14,14
-16,16
-16/fig,16
-18,18
-18/fig,18
-X,1000
-Banned,1001
diff --git a/Emby.Server.Implementations/Localization/Ratings/es.json b/Emby.Server.Implementations/Localization/Ratings/es.json
new file mode 100644
index 000000000..961d64fe7
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/es.json
@@ -0,0 +1,90 @@
+{
+ "countryCode": "es",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["0+", "A", "Ai","A/i", "A/fig", "A/i/fig", "APTA", "ERI", "TP"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["6+"],
+ "ratingScore": {
+ "score": 6,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["7", "7i", "7/i", "7/fig", "7/i/fig"],
+ "ratingScore": {
+ "score": 11,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["9+"],
+ "ratingScore": {
+ "score": 9,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["10"],
+ "ratingScore": {
+ "score": 10,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12", "12/fig"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["13"],
+ "ratingScore": {
+ "score": 13,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["14"],
+ "ratingScore": {
+ "score": 14,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["16", "16/fig"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18", "18/fig"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["X"],
+ "ratingScore": {
+ "score": 1000,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["Banned"],
+ "ratingScore": {
+ "score": 1001,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/fi.csv b/Emby.Server.Implementations/Localization/Ratings/fi.csv
deleted file mode 100644
index 7ff92f259..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/fi.csv
+++ /dev/null
@@ -1,10 +0,0 @@
-S,0
-T,0
-K7,7
-7,7
-K12,12
-12,12
-K16,16
-16,16
-K18,18
-18,18
diff --git a/Emby.Server.Implementations/Localization/Ratings/fi.json b/Emby.Server.Implementations/Localization/Ratings/fi.json
new file mode 100644
index 000000000..0d55af65c
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/fi.json
@@ -0,0 +1,48 @@
+{
+ "countryCode": "fi",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["S", "T"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["7", "K7", "K-7"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12", "K12", "K-12"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["16", "K16", "K-16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18", "K18", "K-18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["KK"],
+ "ratingScore": {
+ "score": 1001,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/fr.csv b/Emby.Server.Implementations/Localization/Ratings/fr.csv
deleted file mode 100644
index 139ea376b..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/fr.csv
+++ /dev/null
@@ -1,13 +0,0 @@
-Public Averti,0
-Tous Publics,0
-TP,0
-U,0
-0+,0
-6+,6
-9+,9
-10,10
-12,12
-14+,14
-16,16
-18,18
-X,1000
diff --git a/Emby.Server.Implementations/Localization/Ratings/fr.json b/Emby.Server.Implementations/Localization/Ratings/fr.json
new file mode 100644
index 000000000..e8bafd6b8
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/fr.json
@@ -0,0 +1,69 @@
+{
+ "countryCode": "fr",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["0+", "Public Averti", "Tous Publics", "TP", "U"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["6+"],
+ "ratingScore": {
+ "score": 6,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["9+"],
+ "ratingScore": {
+ "score": 9,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["10"],
+ "ratingScore": {
+ "score": 10,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["14+"],
+ "ratingScore": {
+ "score": 14,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["X"],
+ "ratingScore": {
+ "score": 1000,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/gb.csv b/Emby.Server.Implementations/Localization/Ratings/gb.csv
deleted file mode 100644
index 858b9a32d..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/gb.csv
+++ /dev/null
@@ -1,23 +0,0 @@
-All,0
-E,0
-G,0
-U,0
-0+,0
-6+,6
-7+,7
-PG,8
-9,9
-12,12
-12+,12
-12A,12
-12PG,12
-Teen,13
-13+,13
-14+,14
-15,15
-16,16
-Caution,18
-18,18
-Mature,1000
-Adult,1000
-R18,1000
diff --git a/Emby.Server.Implementations/Localization/Ratings/gb.json b/Emby.Server.Implementations/Localization/Ratings/gb.json
new file mode 100644
index 000000000..7fc88272c
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/gb.json
@@ -0,0 +1,97 @@
+{
+ "countryCode": "gb",
+ "supportsSubScores": true,
+ "ratings": [
+ {
+ "ratingStrings": ["0+", "All", "E", "G", "U"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["6+"],
+ "ratingScore": {
+ "score": 6,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["7+"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["PG"],
+ "ratingScore": {
+ "score": 8,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["9"],
+ "ratingScore": {
+ "score": 9,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["12A", "12PG"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["12", "12+"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["13+", "Teen"],
+ "ratingScore": {
+ "score": 13,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["14+"],
+ "ratingScore": {
+ "score": 14,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["15"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": 3
+ }
+ },
+ {
+ "ratingStrings": ["16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["18", "Caution"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["Mature", "Adult", "R18"],
+ "ratingScore": {
+ "score": 1000,
+ "subScore": 0
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/gr.json b/Emby.Server.Implementations/Localization/Ratings/gr.json
new file mode 100644
index 000000000..794bf0b31
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/gr.json
@@ -0,0 +1,34 @@
+{
+ "countryCode": "gr",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["K"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["K12"],
+ "ratingScore": {
+ "score": 13,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["K15"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["K18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/hu.json b/Emby.Server.Implementations/Localization/Ratings/hu.json
new file mode 100644
index 000000000..8043451e2
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/hu.json
@@ -0,0 +1,41 @@
+{
+ "countryCode": "hu",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["KN"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["6"],
+ "ratingScore": {
+ "score": 6,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18", "X"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/id.json b/Emby.Server.Implementations/Localization/Ratings/id.json
new file mode 100644
index 000000000..8c687c232
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/id.json
@@ -0,0 +1,34 @@
+{
+ "countryCode": "id",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["SU"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["13+"],
+ "ratingScore": {
+ "score": 13,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["17+"],
+ "ratingScore": {
+ "score": 17,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["21+"],
+ "ratingScore": {
+ "score": 21,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/ie.csv b/Emby.Server.Implementations/Localization/Ratings/ie.csv
deleted file mode 100644
index d3c634fc9..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/ie.csv
+++ /dev/null
@@ -1,10 +0,0 @@
-G,4
-PG,12
-12,12
-12A,12
-12PG,12
-15,15
-15PG,15
-15A,15
-16,16
-18,18
diff --git a/Emby.Server.Implementations/Localization/Ratings/ie.json b/Emby.Server.Implementations/Localization/Ratings/ie.json
new file mode 100644
index 000000000..f6cc56ed6
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/ie.json
@@ -0,0 +1,55 @@
+{
+ "countryCode": "ie",
+ "supportsSubScores": true,
+ "ratings": [
+ {
+ "ratingStrings": ["G"],
+ "ratingScore": {
+ "score": 4,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["12A", "12PG", "PG"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["12"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["15A", "15PG"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["15"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": 3
+ }
+ },
+ {
+ "ratingStrings": ["16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": 1
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/in.json b/Emby.Server.Implementations/Localization/Ratings/in.json
new file mode 100644
index 000000000..d6e6f80ed
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/in.json
@@ -0,0 +1,55 @@
+{
+ "countryCode": "in",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["U"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["U/A 7+"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["UA"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["U/A 13+"],
+ "ratingScore": {
+ "score": 13,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["U/A 16+"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["A"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["S"],
+ "ratingScore": {
+ "score": 1001,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/it.json b/Emby.Server.Implementations/Localization/Ratings/it.json
new file mode 100644
index 000000000..f2889bf82
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/it.json
@@ -0,0 +1,34 @@
+{
+ "countryCode": "it",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["T"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["6+"],
+ "ratingScore": {
+ "score": 6,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["14+"],
+ "ratingScore": {
+ "score": 14,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18+"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/jp.csv b/Emby.Server.Implementations/Localization/Ratings/jp.csv
deleted file mode 100644
index bfb5fdaae..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/jp.csv
+++ /dev/null
@@ -1,11 +0,0 @@
-A,0
-G,0
-B,12
-PG12,12
-C,15
-15+,15
-R15+,15
-16+,16
-D,17
-Z,18
-18+,18
diff --git a/Emby.Server.Implementations/Localization/Ratings/jp.json b/Emby.Server.Implementations/Localization/Ratings/jp.json
new file mode 100644
index 000000000..efff9e92c
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/jp.json
@@ -0,0 +1,62 @@
+{
+ "countryCode": "jp",
+ "supportsSubScores": true,
+ "ratings": [
+ {
+ "ratingStrings": ["A", "G"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["PG12"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["B"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["15A", "15PG"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["C", "15+", "R15+"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["16+"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["D"],
+ "ratingScore": {
+ "score": 17,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18+", "Z"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/kr.json b/Emby.Server.Implementations/Localization/Ratings/kr.json
new file mode 100644
index 000000000..5c416a5e4
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/kr.json
@@ -0,0 +1,41 @@
+{
+ "countryCode": "kr",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["ALL"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["15"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["19"],
+ "ratingScore": {
+ "score": 19,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["Restricted Screening"],
+ "ratingScore": {
+ "score": 1001,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/kz.csv b/Emby.Server.Implementations/Localization/Ratings/kz.csv
deleted file mode 100644
index e26b32b67..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/kz.csv
+++ /dev/null
@@ -1,6 +0,0 @@
-K,0
-БА,12
-Б14,14
-E16,16
-E18,18
-HA,18
diff --git a/Emby.Server.Implementations/Localization/Ratings/kz.json b/Emby.Server.Implementations/Localization/Ratings/kz.json
new file mode 100644
index 000000000..0f8f0c68e
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/kz.json
@@ -0,0 +1,41 @@
+{
+ "countryCode": "kz",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["K"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["БА"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["Б14"],
+ "ratingScore": {
+ "score": 14,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["E16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["E18", "HA"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/lt.json b/Emby.Server.Implementations/Localization/Ratings/lt.json
new file mode 100644
index 000000000..c7b85a760
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/lt.json
@@ -0,0 +1,41 @@
+{
+ "countryCode": "lt",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["V"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["N-7"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["N-13"],
+ "ratingScore": {
+ "score": 13,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["N-16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["N-18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/mx.csv b/Emby.Server.Implementations/Localization/Ratings/mx.csv
deleted file mode 100644
index 305912f23..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/mx.csv
+++ /dev/null
@@ -1,6 +0,0 @@
-A,0
-AA,0
-B,12
-B-15,15
-C,18
-D,1000
diff --git a/Emby.Server.Implementations/Localization/Ratings/mx.json b/Emby.Server.Implementations/Localization/Ratings/mx.json
new file mode 100644
index 000000000..9dc3b89bd
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/mx.json
@@ -0,0 +1,41 @@
+{
+ "countryCode": "mx",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["A", "AA"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["B"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["B-15"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["C"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["D"],
+ "ratingScore": {
+ "score": 1000,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/nl.csv b/Emby.Server.Implementations/Localization/Ratings/nl.csv
deleted file mode 100644
index 44f372b2d..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/nl.csv
+++ /dev/null
@@ -1,8 +0,0 @@
-AL,0
-MG6,6
-6,6
-9,9
-12,12
-14,14
-16,16
-18,18
diff --git a/Emby.Server.Implementations/Localization/Ratings/nl.json b/Emby.Server.Implementations/Localization/Ratings/nl.json
new file mode 100644
index 000000000..2e43eb83a
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/nl.json
@@ -0,0 +1,55 @@
+{
+ "countryCode": "nl",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["AL"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["6", "MG6"],
+ "ratingScore": {
+ "score": 6,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["9"],
+ "ratingScore": {
+ "score": 9,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["14"],
+ "ratingScore": {
+ "score": 14,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/no.csv b/Emby.Server.Implementations/Localization/Ratings/no.csv
deleted file mode 100644
index 6856a2dbb..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/no.csv
+++ /dev/null
@@ -1,10 +0,0 @@
-A,0
-6,6
-7,7
-9,9
-11,11
-12,12
-15,15
-18,18
-C,18
-Not approved,1001
diff --git a/Emby.Server.Implementations/Localization/Ratings/no.json b/Emby.Server.Implementations/Localization/Ratings/no.json
new file mode 100644
index 000000000..a5e952316
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/no.json
@@ -0,0 +1,69 @@
+{
+ "countryCode": "no",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["A"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["6"],
+ "ratingScore": {
+ "score": 6,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["7"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["9"],
+ "ratingScore": {
+ "score": 9,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["11"],
+ "ratingScore": {
+ "score": 11,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["15"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["Not approved"],
+ "ratingScore": {
+ "score": 1001,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/nz.csv b/Emby.Server.Implementations/Localization/Ratings/nz.csv
deleted file mode 100644
index 633da78fe..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/nz.csv
+++ /dev/null
@@ -1,16 +0,0 @@
-Exempt,0
-G,0
-GY,13
-PG,13
-R13,13
-RP13,13
-R15,15
-M,16
-R16,16
-RP16,16
-GA,18
-R18,18
-RP18,18
-MA,1000
-R,1001
-Objectionable,1001
diff --git a/Emby.Server.Implementations/Localization/Ratings/nz.json b/Emby.Server.Implementations/Localization/Ratings/nz.json
new file mode 100644
index 000000000..23b23c8ca
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/nz.json
@@ -0,0 +1,76 @@
+{
+ "countryCode": "nz",
+ "supportsSubScores": true,
+ "ratings": [
+ {
+ "ratingStrings": ["Exempt", "G"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["RP13", "PG"],
+ "ratingScore": {
+ "score": 13,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["GY", "R13"],
+ "ratingScore": {
+ "score": 13,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["R15"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["RP16", "M"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["R16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["RP18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["R18", "GA"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["MA"],
+ "ratingScore": {
+ "score": 1000,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["Objectionable", "R"],
+ "ratingScore": {
+ "score": 1001,
+ "subScore": 0
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/ph.json b/Emby.Server.Implementations/Localization/Ratings/ph.json
new file mode 100644
index 000000000..0bce9df8f
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/ph.json
@@ -0,0 +1,48 @@
+{
+ "countryCode": "ph",
+ "supportsSubScores": true,
+ "ratings": [
+ {
+ "ratingStrings": ["G"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["PG"],
+ "ratingScore": {
+ "score": 13,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["R-13"],
+ "ratingScore": {
+ "score": 13,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["R-16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["R-18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["X"],
+ "ratingScore": {
+ "score": 1001,
+ "subScore": 0
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/pl.json b/Emby.Server.Implementations/Localization/Ratings/pl.json
new file mode 100644
index 000000000..c3001ffb3
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/pl.json
@@ -0,0 +1,41 @@
+{
+ "countryCode": "pl",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["b.o.", "AL"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["7", "od 7 lat"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12", "od 12 lat"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["16", "od 16 lat"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18", "od 18 lat", "R"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/pt.json b/Emby.Server.Implementations/Localization/Ratings/pt.json
new file mode 100644
index 000000000..2ab796c84
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/pt.json
@@ -0,0 +1,62 @@
+{
+ "countryCode": "pt",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["Públicos"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["M/3"],
+ "ratingScore": {
+ "score": 3,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["M/6"],
+ "ratingScore": {
+ "score": 6,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["M/12"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["M/14"],
+ "ratingScore": {
+ "score": 14,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["M/16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["M/18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["P"],
+ "ratingScore": {
+ "score": 1000,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/ro.csv b/Emby.Server.Implementations/Localization/Ratings/ro.csv
deleted file mode 100644
index 44c23e248..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/ro.csv
+++ /dev/null
@@ -1,6 +0,0 @@
-AG,0
-AP-12,12
-N-15,15
-IM-18,18
-IM-18-XXX,1000
-IC,1001
diff --git a/Emby.Server.Implementations/Localization/Ratings/ro.json b/Emby.Server.Implementations/Localization/Ratings/ro.json
new file mode 100644
index 000000000..aa6f7fe55
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/ro.json
@@ -0,0 +1,48 @@
+{
+ "countryCode": "ro",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["AG", "AP"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12", "AP-12"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["15", "N-15"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18", "IM-18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18+", "IM-18-XXX"],
+ "ratingScore": {
+ "score": 1000,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["IC"],
+ "ratingScore": {
+ "score": 1001,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/ru.csv b/Emby.Server.Implementations/Localization/Ratings/ru.csv
deleted file mode 100644
index 8b264070b..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/ru.csv
+++ /dev/null
@@ -1,6 +0,0 @@
-0+,0
-6+,6
-12+,12
-16+,16
-18+,18
-Refused classification,1001
diff --git a/Emby.Server.Implementations/Localization/Ratings/ru.json b/Emby.Server.Implementations/Localization/Ratings/ru.json
new file mode 100644
index 000000000..d1b8b13aa
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/ru.json
@@ -0,0 +1,48 @@
+{
+ "countryCode": "ru",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["0+"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["6+"],
+ "ratingScore": {
+ "score": 6,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12+"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["16+"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18+"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["Refused classification"],
+ "ratingScore": {
+ "score": 1001,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/se.csv b/Emby.Server.Implementations/Localization/Ratings/se.csv
deleted file mode 100644
index e129c3561..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/se.csv
+++ /dev/null
@@ -1,10 +0,0 @@
-Alla,0
-Barntillåten,0
-Btl,0
-0+,0
-7,7
-9+,9
-10+,10
-11,11
-14,14
-15,15
diff --git a/Emby.Server.Implementations/Localization/Ratings/se.json b/Emby.Server.Implementations/Localization/Ratings/se.json
new file mode 100644
index 000000000..70084995d
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/se.json
@@ -0,0 +1,55 @@
+{
+ "countryCode": "se",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["0+", "Alla", "Barntillåten", "Btl"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["7"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["9+"],
+ "ratingScore": {
+ "score": 9,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["10+"],
+ "ratingScore": {
+ "score": 10,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["11"],
+ "ratingScore": {
+ "score": 11,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["14"],
+ "ratingScore": {
+ "score": 14,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["15"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/sg.json b/Emby.Server.Implementations/Localization/Ratings/sg.json
new file mode 100644
index 000000000..47d9e2833
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/sg.json
@@ -0,0 +1,48 @@
+{
+ "countryCode": "sg",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["G"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["PG"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["PG13"],
+ "ratingScore": {
+ "score": 13,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["NC16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["M18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["R21"],
+ "ratingScore": {
+ "score": 21,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/sk.csv b/Emby.Server.Implementations/Localization/Ratings/sk.csv
deleted file mode 100644
index dbafd8efa..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/sk.csv
+++ /dev/null
@@ -1,6 +0,0 @@
-NR,0
-U,0
-7,7
-12,12
-15,15
-18,18
diff --git a/Emby.Server.Implementations/Localization/Ratings/sk.json b/Emby.Server.Implementations/Localization/Ratings/sk.json
new file mode 100644
index 000000000..5ec6111ec
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/sk.json
@@ -0,0 +1,41 @@
+{
+ "countryCode": "sk",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["U", "NR"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["7"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["15"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/th.json b/Emby.Server.Implementations/Localization/Ratings/th.json
new file mode 100644
index 000000000..44bfab21c
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/th.json
@@ -0,0 +1,48 @@
+{
+ "countryCode": "th",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["P", "G"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["13"],
+ "ratingScore": {
+ "score": 13,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["15"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18+"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["20"],
+ "ratingScore": {
+ "score": 20,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["Banned"],
+ "ratingScore": {
+ "score": 1001,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/tr.json b/Emby.Server.Implementations/Localization/Ratings/tr.json
new file mode 100644
index 000000000..5a3868856
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/tr.json
@@ -0,0 +1,69 @@
+{
+ "countryCode": "tr",
+ "supportsSubScores": true,
+ "ratings": [
+ {
+ "ratingStrings": ["Genel İzleyici Kitlesi"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["6A"],
+ "ratingScore": {
+ "score": 6,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["6+"],
+ "ratingScore": {
+ "score": 6,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["10A"],
+ "ratingScore": {
+ "score": 10,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["10+"],
+ "ratingScore": {
+ "score": 10,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["13A"],
+ "ratingScore": {
+ "score": 13,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["13+"],
+ "ratingScore": {
+ "score": 13,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["16+"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["18+"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": 0
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/tw.json b/Emby.Server.Implementations/Localization/Ratings/tw.json
new file mode 100644
index 000000000..a7869c122
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/tw.json
@@ -0,0 +1,41 @@
+{
+ "countryCode": "tw",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["0+"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["6+"],
+ "ratingScore": {
+ "score": 6,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12+"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["15+"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18+"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/ua.json b/Emby.Server.Implementations/Localization/Ratings/ua.json
new file mode 100644
index 000000000..d8fe95168
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/ua.json
@@ -0,0 +1,34 @@
+{
+ "countryCode": "ua",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["0+"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["12+"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["16+"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18+"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/uk.csv b/Emby.Server.Implementations/Localization/Ratings/uk.csv
deleted file mode 100644
index 75b1c2058..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/uk.csv
+++ /dev/null
@@ -1,22 +0,0 @@
-All,0
-E,0
-G,0
-U,0
-0+,0
-6+,6
-7+,7
-PG,8
-9+,9
-12,12
-12+,12
-12A,12
-Teen,13
-13+,13
-14+,14
-15,15
-16,16
-Caution,18
-18,18
-Mature,1000
-Adult,1000
-R18,1000
diff --git a/Emby.Server.Implementations/Localization/Ratings/uk.json b/Emby.Server.Implementations/Localization/Ratings/uk.json
new file mode 100644
index 000000000..7fc88272c
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/uk.json
@@ -0,0 +1,97 @@
+{
+ "countryCode": "gb",
+ "supportsSubScores": true,
+ "ratings": [
+ {
+ "ratingStrings": ["0+", "All", "E", "G", "U"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["6+"],
+ "ratingScore": {
+ "score": 6,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["7+"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["PG"],
+ "ratingScore": {
+ "score": 8,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["9"],
+ "ratingScore": {
+ "score": 9,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["12A", "12PG"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["12", "12+"],
+ "ratingScore": {
+ "score": 12,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["13+", "Teen"],
+ "ratingScore": {
+ "score": 13,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["14+"],
+ "ratingScore": {
+ "score": 14,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["15"],
+ "ratingScore": {
+ "score": 15,
+ "subScore": 3
+ }
+ },
+ {
+ "ratingStrings": ["16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["18", "Caution"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["Mature", "Adult", "R18"],
+ "ratingScore": {
+ "score": 1000,
+ "subScore": 0
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/us.csv b/Emby.Server.Implementations/Localization/Ratings/us.csv
deleted file mode 100644
index 9aa5c00eb..000000000
--- a/Emby.Server.Implementations/Localization/Ratings/us.csv
+++ /dev/null
@@ -1,52 +0,0 @@
-Approved,0
-G,0
-TV-G,0
-TV-Y,0
-TV-Y7,7
-TV-Y7-FV,7
-PG,10
-TV-PG,10
-TV-PG-D,10
-TV-PG-L,10
-TV-PG-S,10
-TV-PG-V,10
-TV-PG-DL,10
-TV-PG-DS,10
-TV-PG-DV,10
-TV-PG-LS,10
-TV-PG-LV,10
-TV-PG-SV,10
-TV-PG-DLS,10
-TV-PG-DLV,10
-TV-PG-DSV,10
-TV-PG-LSV,10
-TV-PG-DLSV,10
-PG-13,13
-TV-14,14
-TV-14-D,14
-TV-14-L,14
-TV-14-S,14
-TV-14-V,14
-TV-14-DL,14
-TV-14-DS,14
-TV-14-DV,14
-TV-14-LS,14
-TV-14-LV,14
-TV-14-SV,14
-TV-14-DLS,14
-TV-14-DLV,14
-TV-14-DSV,14
-TV-14-LSV,14
-TV-14-DLSV,14
-NC-17,17
-R,17
-TV-MA,17
-TV-MA-L,17
-TV-MA-S,17
-TV-MA-V,17
-TV-MA-LS,17
-TV-MA-LV,17
-TV-MA-SV,17
-TV-MA-LSV,17
-TV-X,18
-TV-AO,18
diff --git a/Emby.Server.Implementations/Localization/Ratings/us.json b/Emby.Server.Implementations/Localization/Ratings/us.json
new file mode 100644
index 000000000..08a637312
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/us.json
@@ -0,0 +1,83 @@
+{
+ "countryCode": "us",
+ "supportsSubScores": true,
+ "ratings": [
+ {
+ "ratingStrings": ["Approved", "G", "TV-G", "TV-Y"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["TV-Y7"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["TV-Y7-FV"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["PG", "TV-PG"],
+ "ratingScore": {
+ "score": 10,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["TV-PG-D", "TV-PG-L", "TV-PG-S", "TV-PG-V", "TV-PG-DL", "TV-PG-DS", "TV-PG-DV", "TV-PG-LS", "TV-PG-LV", "TV-PG-SV", "TV-PG-DLS", "TV-PG-DLV", "TV-PG-DSV", "TV-PG-LSV", "TV-PG-DLSV"],
+ "ratingScore": {
+ "score": 10,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["PG-13"],
+ "ratingScore": {
+ "score": 13,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["TV-14"],
+ "ratingScore": {
+ "score": 14,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["TV-14-D", "TV-14-L", "TV-14-S", "TV-14-V", "TV-14-DL", "TV-14-DS", "TV-14-DV", "TV-14-LS", "TV-14-LV", "TV-14-SV", "TV-14-DLS", "TV-14-DLV", "TV-14-DSV", "TV-14-LSV", "TV-14-DLSV"],
+ "ratingScore": {
+ "score": 14,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["R"],
+ "ratingScore": {
+ "score": 17,
+ "subScore": 0
+ }
+ },
+ {
+ "ratingStrings": ["NC-17", "TV-MA", "TV-MA-L", "TV-MA-S", "TV-MA-V", "TV-MA-LS", "TV-MA-LV", "TV-MA-SV", "TV-MA-LSV"],
+ "ratingScore": {
+ "score": 17,
+ "subScore": 1
+ }
+ },
+ {
+ "ratingStrings": ["TV-X", "TV-AO"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": 0
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/Ratings/za.json b/Emby.Server.Implementations/Localization/Ratings/za.json
new file mode 100644
index 000000000..fe13af797
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Ratings/za.json
@@ -0,0 +1,55 @@
+{
+ "countryCode": "za",
+ "supportsSubScores": false,
+ "ratings": [
+ {
+ "ratingStrings": ["A"],
+ "ratingScore": {
+ "score": 0,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["PG", "7-9PG"],
+ "ratingScore": {
+ "score": 7,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["10-12PG"],
+ "ratingScore": {
+ "score": 10,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["13"],
+ "ratingScore": {
+ "score": 13,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["16"],
+ "ratingScore": {
+ "score": 16,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["18"],
+ "ratingScore": {
+ "score": 18,
+ "subScore": null
+ }
+ },
+ {
+ "ratingStrings": ["X18", "XX"],
+ "ratingScore": {
+ "score": 1001,
+ "subScore": null
+ }
+ }
+ ]
+}
diff --git a/Emby.Server.Implementations/Localization/iso6392.txt b/Emby.Server.Implementations/Localization/iso6392.txt
index 00c2aee62..42bb46d7d 100644
--- a/Emby.Server.Implementations/Localization/iso6392.txt
+++ b/Emby.Server.Implementations/Localization/iso6392.txt
@@ -347,8 +347,8 @@ pli||pi|Pali|pali
pol||pl|Polish|polonais
pon|||Pohnpeian|pohnpei
por||pt|Portuguese|portugais
-pop||pt-pt|Portuguese (Portugal)|portugais (pt-pt)
-pob||pt-br|Portuguese (Brazil)|portugais (pt-br)
+por||pt-pt|Portuguese (Portugal)|portugais (pt-pt)
+por||pt-br|Portuguese (Brazil)|portugais (pt-br)
pra|||Prakrit languages|prâkrit, langues
pro|||Provençal, Old (to 1500)|provençal ancien (jusqu'à 1500)
pus||ps|Pushto; Pashto|pachto
diff --git a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs
deleted file mode 100644
index ea7896861..000000000
--- a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs
+++ /dev/null
@@ -1,272 +0,0 @@
-#nullable disable
-
-#pragma warning disable CS1591
-
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Jellyfin.Extensions;
-using MediaBrowser.Controller.Chapters;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.MediaEncoder
-{
- public class EncodingManager : IEncodingManager
- {
- private readonly IFileSystem _fileSystem;
- private readonly ILogger<EncodingManager> _logger;
- private readonly IMediaEncoder _encoder;
- private readonly IChapterRepository _chapterManager;
- private readonly ILibraryManager _libraryManager;
-
- /// <summary>
- /// The first chapter ticks.
- /// </summary>
- private static readonly long _firstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
-
- public EncodingManager(
- ILogger<EncodingManager> logger,
- IFileSystem fileSystem,
- IMediaEncoder encoder,
- IChapterRepository chapterManager,
- ILibraryManager libraryManager)
- {
- _logger = logger;
- _fileSystem = fileSystem;
- _encoder = encoder;
- _chapterManager = chapterManager;
- _libraryManager = libraryManager;
- }
-
- /// <summary>
- /// Gets the chapter images data path.
- /// </summary>
- /// <value>The chapter images data path.</value>
- private static string GetChapterImagesPath(BaseItem item)
- {
- return Path.Combine(item.GetInternalMetadataPath(), "chapters");
- }
-
- /// <summary>
- /// Determines whether [is eligible for chapter image extraction] [the specified video].
- /// </summary>
- /// <param name="video">The video.</param>
- /// <param name="libraryOptions">The library options for the video.</param>
- /// <returns><c>true</c> if [is eligible for chapter image extraction] [the specified video]; otherwise, <c>false</c>.</returns>
- private bool IsEligibleForChapterImageExtraction(Video video, LibraryOptions libraryOptions)
- {
- if (video.IsPlaceHolder)
- {
- return false;
- }
-
- if (libraryOptions is null || !libraryOptions.EnableChapterImageExtraction)
- {
- return false;
- }
-
- if (video.IsShortcut)
- {
- return false;
- }
-
- if (!video.IsCompleteMedia)
- {
- return false;
- }
-
- // Can't extract images if there are no video streams
- return video.DefaultVideoStreamIndex.HasValue;
- }
-
- private long GetAverageDurationBetweenChapters(IReadOnlyList<ChapterInfo> chapters)
- {
- if (chapters.Count < 2)
- {
- return 0;
- }
-
- long sum = 0;
- for (int i = 1; i < chapters.Count; i++)
- {
- sum += chapters[i].StartPositionTicks - chapters[i - 1].StartPositionTicks;
- }
-
- return sum / chapters.Count;
- }
-
- public async Task<bool> RefreshChapterImages(Video video, IDirectoryService directoryService, IReadOnlyList<ChapterInfo> chapters, bool extractImages, bool saveChapters, CancellationToken cancellationToken)
- {
- if (chapters.Count == 0)
- {
- return true;
- }
-
- var libraryOptions = _libraryManager.GetLibraryOptions(video);
-
- if (!IsEligibleForChapterImageExtraction(video, libraryOptions))
- {
- extractImages = false;
- }
-
- var averageChapterDuration = GetAverageDurationBetweenChapters(chapters);
- var threshold = TimeSpan.FromSeconds(1).Ticks;
- if (averageChapterDuration < threshold)
- {
- _logger.LogInformation("Skipping chapter image extraction for {Video} as the average chapter duration {AverageDuration} was lower than the minimum threshold {Threshold}", video.Name, averageChapterDuration, threshold);
- extractImages = false;
- }
-
- var success = true;
- var changesMade = false;
-
- var runtimeTicks = video.RunTimeTicks ?? 0;
-
- var currentImages = GetSavedChapterImages(video, directoryService);
-
- foreach (var chapter in chapters)
- {
- if (chapter.StartPositionTicks >= runtimeTicks)
- {
- _logger.LogInformation("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
- break;
- }
-
- var path = GetChapterImagePath(video, chapter.StartPositionTicks);
-
- if (!currentImages.Contains(path, StringComparison.OrdinalIgnoreCase))
- {
- if (extractImages)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- try
- {
- // Add some time for the first chapter to make sure we don't end up with a black image
- var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(_firstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
-
- var inputPath = video.Path;
-
- Directory.CreateDirectory(Path.GetDirectoryName(path));
-
- var container = video.Container;
- var mediaSource = new MediaSourceInfo
- {
- VideoType = video.VideoType,
- IsoType = video.IsoType,
- Protocol = video.PathProtocol.Value,
- };
-
- var tempFile = await _encoder.ExtractVideoImage(inputPath, container, mediaSource, video.GetDefaultVideoStream(), video.Video3DFormat, time, cancellationToken).ConfigureAwait(false);
- File.Copy(tempFile, path, true);
-
- try
- {
- _fileSystem.DeleteFile(tempFile);
- }
- catch (IOException ex)
- {
- _logger.LogError(ex, "Error deleting temporary chapter image encoding file {Path}", tempFile);
- }
-
- chapter.ImagePath = path;
- chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
- changesMade = true;
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error extracting chapter images for {0}", string.Join(',', video.Path));
- success = false;
- break;
- }
- }
- else if (!string.IsNullOrEmpty(chapter.ImagePath))
- {
- chapter.ImagePath = null;
- changesMade = true;
- }
- }
- else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
- {
- chapter.ImagePath = path;
- chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
- changesMade = true;
- }
- else if (libraryOptions?.EnableChapterImageExtraction != true)
- {
- // We have an image for the current chapter but the user has disabled chapter image extraction -> delete this chapter's image
- chapter.ImagePath = null;
- changesMade = true;
- }
- }
-
- if (saveChapters && changesMade)
- {
- _chapterManager.SaveChapters(video.Id, chapters);
- }
-
- DeleteDeadImages(currentImages, chapters);
-
- return success;
- }
-
- private string GetChapterImagePath(Video video, long chapterPositionTicks)
- {
- var filename = video.DateModified.Ticks.ToString(CultureInfo.InvariantCulture) + "_" + chapterPositionTicks.ToString(CultureInfo.InvariantCulture) + ".jpg";
-
- return Path.Combine(GetChapterImagesPath(video), filename);
- }
-
- private static IReadOnlyList<string> GetSavedChapterImages(Video video, IDirectoryService directoryService)
- {
- var path = GetChapterImagesPath(video);
- if (!Directory.Exists(path))
- {
- return Array.Empty<string>();
- }
-
- try
- {
- return directoryService.GetFilePaths(path);
- }
- catch (IOException)
- {
- return Array.Empty<string>();
- }
- }
-
- private void DeleteDeadImages(IEnumerable<string> images, IEnumerable<ChapterInfo> chapters)
- {
- var deadImages = images
- .Except(chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i)), StringComparer.OrdinalIgnoreCase)
- .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i.AsSpan()), StringComparison.OrdinalIgnoreCase))
- .ToList();
-
- foreach (var image in deadImages)
- {
- _logger.LogDebug("Deleting dead chapter image {Path}", image);
-
- try
- {
- _fileSystem.DeleteFile(image);
- }
- catch (IOException ex)
- {
- _logger.LogError(ex, "Error deleting {Path}.", image);
- }
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/Playlists/PlaylistManager.cs b/Emby.Server.Implementations/Playlists/PlaylistManager.cs
index 7b0a16441..1ce363de5 100644
--- a/Emby.Server.Implementations/Playlists/PlaylistManager.cs
+++ b/Emby.Server.Implementations/Playlists/PlaylistManager.cs
@@ -134,14 +134,16 @@ namespace Emby.Server.Implementations.Playlists
try
{
- Directory.CreateDirectory(path);
+ var info = Directory.CreateDirectory(path);
var playlist = new Playlist
{
Name = name,
Path = path,
OwnerUserId = request.UserId,
Shares = request.Users ?? [],
- OpenAccess = request.Public ?? false
+ OpenAccess = request.Public ?? false,
+ DateCreated = info.CreationTimeUtc,
+ DateModified = info.LastWriteTimeUtc
};
playlist.SetMediaType(request.MediaType);
@@ -283,6 +285,16 @@ namespace Emby.Server.Implementations.Playlists
RefreshPriority.High);
}
+ internal static int DetermineAdjustedIndex(int newPriorIndexAllChildren, int newIndex)
+ {
+ if (newIndex == 0)
+ {
+ return newPriorIndexAllChildren > 0 ? newPriorIndexAllChildren - 1 : 0;
+ }
+
+ return newPriorIndexAllChildren + 1;
+ }
+
public async Task MoveItemAsync(string playlistId, string entryId, int newIndex, Guid callingUserId)
{
if (_libraryManager.GetItemById(playlistId) is not Playlist playlist)
@@ -305,7 +317,7 @@ namespace Emby.Server.Implementations.Playlists
var newPriorItemIndex = newIndex > oldIndexAccessible ? newIndex : newIndex - 1 < 0 ? 0 : newIndex - 1;
var newPriorItemId = accessibleChildren[newPriorItemIndex].Item1.ItemId;
var newPriorItemIndexOnAllChildren = children.FindIndex(c => c.Item1.ItemId.Equals(newPriorItemId));
- var adjustedNewIndex = newPriorItemIndexOnAllChildren + 1;
+ var adjustedNewIndex = DetermineAdjustedIndex(newPriorItemIndexOnAllChildren, newIndex);
var item = playlist.LinkedChildren.FirstOrDefault(i => string.Equals(entryId, i.ItemId?.ToString("N", CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase));
if (item is null)
diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs
index 985f0a8f8..24f554981 100644
--- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs
@@ -16,663 +16,662 @@ using MediaBrowser.Common.Extensions;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.ScheduledTasks
+namespace Emby.Server.Implementations.ScheduledTasks;
+
+/// <summary>
+/// Class ScheduledTaskWorker.
+/// </summary>
+public class ScheduledTaskWorker : IScheduledTaskWorker
{
+ private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
+ private readonly IApplicationPaths _applicationPaths;
+ private readonly ILogger _logger;
+ private readonly ITaskManager _taskManager;
+ private readonly Lock _lastExecutionResultSyncLock = new();
+ private bool _readFromFile;
+ private TaskResult _lastExecutionResult;
+ private Task _currentTask;
+ private Tuple<TaskTriggerInfo, ITaskTrigger>[] _triggers;
+ private string _id;
+
/// <summary>
- /// Class ScheduledTaskWorker.
+ /// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class.
/// </summary>
- public class ScheduledTaskWorker : IScheduledTaskWorker
+ /// <param name="scheduledTask">The scheduled task.</param>
+ /// <param name="applicationPaths">The application paths.</param>
+ /// <param name="taskManager">The task manager.</param>
+ /// <param name="logger">The logger.</param>
+ /// <exception cref="ArgumentNullException">
+ /// scheduledTask
+ /// or
+ /// applicationPaths
+ /// or
+ /// taskManager
+ /// or
+ /// jsonSerializer
+ /// or
+ /// logger.
+ /// </exception>
+ public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, ILogger logger)
{
- private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
- private readonly IApplicationPaths _applicationPaths;
- private readonly ILogger _logger;
- private readonly ITaskManager _taskManager;
- private readonly Lock _lastExecutionResultSyncLock = new();
- private bool _readFromFile;
- private TaskResult _lastExecutionResult;
- private Task _currentTask;
- private Tuple<TaskTriggerInfo, ITaskTrigger>[] _triggers;
- private string _id;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class.
- /// </summary>
- /// <param name="scheduledTask">The scheduled task.</param>
- /// <param name="applicationPaths">The application paths.</param>
- /// <param name="taskManager">The task manager.</param>
- /// <param name="logger">The logger.</param>
- /// <exception cref="ArgumentNullException">
- /// scheduledTask
- /// or
- /// applicationPaths
- /// or
- /// taskManager
- /// or
- /// jsonSerializer
- /// or
- /// logger.
- /// </exception>
- public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, ILogger logger)
- {
- ArgumentNullException.ThrowIfNull(scheduledTask);
- ArgumentNullException.ThrowIfNull(applicationPaths);
- ArgumentNullException.ThrowIfNull(taskManager);
- ArgumentNullException.ThrowIfNull(logger);
+ ArgumentNullException.ThrowIfNull(scheduledTask);
+ ArgumentNullException.ThrowIfNull(applicationPaths);
+ ArgumentNullException.ThrowIfNull(taskManager);
+ ArgumentNullException.ThrowIfNull(logger);
- ScheduledTask = scheduledTask;
- _applicationPaths = applicationPaths;
- _taskManager = taskManager;
- _logger = logger;
+ ScheduledTask = scheduledTask;
+ _applicationPaths = applicationPaths;
+ _taskManager = taskManager;
+ _logger = logger;
- InitTriggerEvents();
- }
+ InitTriggerEvents();
+ }
- /// <inheritdoc />
- public event EventHandler<GenericEventArgs<double>> TaskProgress;
+ /// <inheritdoc />
+ public event EventHandler<GenericEventArgs<double>> TaskProgress;
- /// <inheritdoc />
- public IScheduledTask ScheduledTask { get; private set; }
+ /// <inheritdoc />
+ public IScheduledTask ScheduledTask { get; private set; }
- /// <inheritdoc />
- public TaskResult LastExecutionResult
+ /// <inheritdoc />
+ public TaskResult LastExecutionResult
+ {
+ get
{
- get
- {
- var path = GetHistoryFilePath();
+ var path = GetHistoryFilePath();
- lock (_lastExecutionResultSyncLock)
+ lock (_lastExecutionResultSyncLock)
+ {
+ if (_lastExecutionResult is null && !_readFromFile)
{
- if (_lastExecutionResult is null && !_readFromFile)
+ if (File.Exists(path))
{
- if (File.Exists(path))
+ var bytes = File.ReadAllBytes(path);
+ if (bytes.Length > 0)
{
- var bytes = File.ReadAllBytes(path);
- if (bytes.Length > 0)
+ try
{
- try
- {
- _lastExecutionResult = JsonSerializer.Deserialize<TaskResult>(bytes, _jsonOptions);
- }
- catch (JsonException ex)
- {
- _logger.LogError(ex, "Error deserializing {File}", path);
- }
+ _lastExecutionResult = JsonSerializer.Deserialize<TaskResult>(bytes, _jsonOptions);
}
- else
+ catch (JsonException ex)
{
- _logger.LogDebug("Scheduled Task history file {Path} is empty. Skipping deserialization.", path);
+ _logger.LogError(ex, "Error deserializing {File}", path);
}
}
-
- _readFromFile = true;
+ else
+ {
+ _logger.LogDebug("Scheduled Task history file {Path} is empty. Skipping deserialization.", path);
+ }
}
- }
- return _lastExecutionResult;
+ _readFromFile = true;
+ }
}
- private set
- {
- _lastExecutionResult = value;
+ return _lastExecutionResult;
+ }
- var path = GetHistoryFilePath();
- Directory.CreateDirectory(Path.GetDirectoryName(path));
+ private set
+ {
+ _lastExecutionResult = value;
- lock (_lastExecutionResultSyncLock)
- {
- using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
- using Utf8JsonWriter jsonStream = new Utf8JsonWriter(createStream);
- JsonSerializer.Serialize(jsonStream, value, _jsonOptions);
- }
+ var path = GetHistoryFilePath();
+ Directory.CreateDirectory(Path.GetDirectoryName(path));
+
+ lock (_lastExecutionResultSyncLock)
+ {
+ using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
+ using Utf8JsonWriter jsonStream = new Utf8JsonWriter(createStream);
+ JsonSerializer.Serialize(jsonStream, value, _jsonOptions);
}
}
+ }
- /// <inheritdoc />
- public string Name => ScheduledTask.Name;
+ /// <inheritdoc />
+ public string Name => ScheduledTask.Name;
- /// <inheritdoc />
- public string Description => ScheduledTask.Description;
+ /// <inheritdoc />
+ public string Description => ScheduledTask.Description;
- /// <inheritdoc />
- public string Category => ScheduledTask.Category;
+ /// <inheritdoc />
+ public string Category => ScheduledTask.Category;
- /// <summary>
- /// Gets or sets the current cancellation token.
- /// </summary>
- /// <value>The current cancellation token source.</value>
- private CancellationTokenSource CurrentCancellationTokenSource { get; set; }
+ /// <summary>
+ /// Gets or sets the current cancellation token.
+ /// </summary>
+ /// <value>The current cancellation token source.</value>
+ private CancellationTokenSource CurrentCancellationTokenSource { get; set; }
- /// <summary>
- /// Gets or sets the current execution start time.
- /// </summary>
- /// <value>The current execution start time.</value>
- private DateTime CurrentExecutionStartTime { get; set; }
+ /// <summary>
+ /// Gets or sets the current execution start time.
+ /// </summary>
+ /// <value>The current execution start time.</value>
+ private DateTime CurrentExecutionStartTime { get; set; }
- /// <inheritdoc />
- public TaskState State
+ /// <inheritdoc />
+ public TaskState State
+ {
+ get
{
- get
+ if (CurrentCancellationTokenSource is not null)
{
- if (CurrentCancellationTokenSource is not null)
- {
- return CurrentCancellationTokenSource.IsCancellationRequested
- ? TaskState.Cancelling
- : TaskState.Running;
- }
-
- return TaskState.Idle;
+ return CurrentCancellationTokenSource.IsCancellationRequested
+ ? TaskState.Cancelling
+ : TaskState.Running;
}
+
+ return TaskState.Idle;
}
+ }
- /// <inheritdoc />
- public double? CurrentProgress { get; private set; }
+ /// <inheritdoc />
+ public double? CurrentProgress { get; private set; }
- /// <summary>
- /// Gets or sets the triggers that define when the task will run.
- /// </summary>
- /// <value>The triggers.</value>
- private Tuple<TaskTriggerInfo, ITaskTrigger>[] InternalTriggers
+ /// <summary>
+ /// Gets or sets the triggers that define when the task will run.
+ /// </summary>
+ /// <value>The triggers.</value>
+ private Tuple<TaskTriggerInfo, ITaskTrigger>[] InternalTriggers
+ {
+ get => _triggers;
+ set
{
- get => _triggers;
- set
- {
- ArgumentNullException.ThrowIfNull(value);
+ ArgumentNullException.ThrowIfNull(value);
- // Cleanup current triggers
- if (_triggers is not null)
- {
- DisposeTriggers();
- }
+ // Cleanup current triggers
+ if (_triggers is not null)
+ {
+ DisposeTriggers();
+ }
- _triggers = value.ToArray();
+ _triggers = value.ToArray();
- ReloadTriggerEvents(false);
- }
+ ReloadTriggerEvents(false);
}
+ }
- /// <inheritdoc />
- public IReadOnlyList<TaskTriggerInfo> Triggers
+ /// <inheritdoc />
+ public IReadOnlyList<TaskTriggerInfo> Triggers
+ {
+ get
{
- get
- {
- return Array.ConvertAll(InternalTriggers, i => i.Item1);
- }
+ return Array.ConvertAll(InternalTriggers, i => i.Item1);
+ }
- set
- {
- ArgumentNullException.ThrowIfNull(value);
+ set
+ {
+ ArgumentNullException.ThrowIfNull(value);
- // This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
- var triggerList = value.Where(i => i is not null).ToArray();
+ // This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
+ var triggerList = value.Where(i => i is not null).ToArray();
- SaveTriggers(triggerList);
+ SaveTriggers(triggerList);
- InternalTriggers = Array.ConvertAll(triggerList, i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i)));
- }
+ InternalTriggers = Array.ConvertAll(triggerList, i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i)));
}
+ }
- /// <inheritdoc />
- public string Id
+ /// <inheritdoc />
+ public string Id
+ {
+ get
{
- get
- {
- return _id ??= ScheduledTask.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture);
- }
+ return _id ??= ScheduledTask.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
+ }
- private void InitTriggerEvents()
- {
- _triggers = LoadTriggers();
- ReloadTriggerEvents(true);
- }
+ private void InitTriggerEvents()
+ {
+ _triggers = LoadTriggers();
+ ReloadTriggerEvents(true);
+ }
- /// <inheritdoc />
- public void ReloadTriggerEvents()
- {
- ReloadTriggerEvents(false);
- }
+ /// <inheritdoc />
+ public void ReloadTriggerEvents()
+ {
+ ReloadTriggerEvents(false);
+ }
- /// <summary>
- /// Reloads the trigger events.
- /// </summary>
- /// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
- private void ReloadTriggerEvents(bool isApplicationStartup)
+ /// <summary>
+ /// Reloads the trigger events.
+ /// </summary>
+ /// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
+ private void ReloadTriggerEvents(bool isApplicationStartup)
+ {
+ foreach (var triggerInfo in InternalTriggers)
{
- foreach (var triggerInfo in InternalTriggers)
- {
- var trigger = triggerInfo.Item2;
+ var trigger = triggerInfo.Item2;
- trigger.Stop();
+ trigger.Stop();
- trigger.Triggered -= OnTriggerTriggered;
- trigger.Triggered += OnTriggerTriggered;
- trigger.Start(LastExecutionResult, _logger, Name, isApplicationStartup);
- }
+ trigger.Triggered -= OnTriggerTriggered;
+ trigger.Triggered += OnTriggerTriggered;
+ trigger.Start(LastExecutionResult, _logger, Name, isApplicationStartup);
}
+ }
- /// <summary>
- /// Handles the Triggered event of the trigger control.
- /// </summary>
- /// <param name="sender">The source of the event.</param>
- /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
- private async void OnTriggerTriggered(object sender, EventArgs e)
- {
- var trigger = (ITaskTrigger)sender;
+ /// <summary>
+ /// Handles the Triggered event of the trigger control.
+ /// </summary>
+ /// <param name="sender">The source of the event.</param>
+ /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
+ private async void OnTriggerTriggered(object sender, EventArgs e)
+ {
+ var trigger = (ITaskTrigger)sender;
- if (ScheduledTask is IConfigurableScheduledTask configurableTask && !configurableTask.IsEnabled)
- {
- return;
- }
+ if (ScheduledTask is IConfigurableScheduledTask configurableTask && !configurableTask.IsEnabled)
+ {
+ return;
+ }
- _logger.LogDebug("{0} fired for task: {1}", trigger.GetType().Name, Name);
+ _logger.LogDebug("{0} fired for task: {1}", trigger.GetType().Name, Name);
- trigger.Stop();
+ trigger.Stop();
- _taskManager.QueueScheduledTask(ScheduledTask, trigger.TaskOptions);
+ _taskManager.QueueScheduledTask(ScheduledTask, trigger.TaskOptions);
- await Task.Delay(1000).ConfigureAwait(false);
+ await Task.Delay(1000).ConfigureAwait(false);
- trigger.Start(LastExecutionResult, _logger, Name, false);
- }
+ trigger.Start(LastExecutionResult, _logger, Name, false);
+ }
- /// <summary>
- /// Executes the task.
- /// </summary>
- /// <param name="options">Task options.</param>
- /// <returns>Task.</returns>
- /// <exception cref="InvalidOperationException">Cannot execute a Task that is already running.</exception>
- public async Task Execute(TaskOptions options)
- {
- var task = Task.Run(async () => await ExecuteInternal(options).ConfigureAwait(false));
+ /// <summary>
+ /// Executes the task.
+ /// </summary>
+ /// <param name="options">Task options.</param>
+ /// <returns>Task.</returns>
+ /// <exception cref="InvalidOperationException">Cannot execute a Task that is already running.</exception>
+ public async Task Execute(TaskOptions options)
+ {
+ var task = Task.Run(async () => await ExecuteInternal(options).ConfigureAwait(false));
- _currentTask = task;
+ _currentTask = task;
- try
- {
- await task.ConfigureAwait(false);
- }
- finally
- {
- _currentTask = null;
- GC.Collect();
- }
+ try
+ {
+ await task.ConfigureAwait(false);
}
-
- private async Task ExecuteInternal(TaskOptions options)
+ finally
{
- // Cancel the current execution, if any
- if (CurrentCancellationTokenSource is not null)
- {
- throw new InvalidOperationException("Cannot execute a Task that is already running");
- }
-
- var progress = new Progress<double>();
+ _currentTask = null;
+ GC.Collect();
+ }
+ }
- CurrentCancellationTokenSource = new CancellationTokenSource();
+ private async Task ExecuteInternal(TaskOptions options)
+ {
+ // Cancel the current execution, if any
+ if (CurrentCancellationTokenSource is not null)
+ {
+ throw new InvalidOperationException("Cannot execute a Task that is already running");
+ }
- _logger.LogDebug("Executing {0}", Name);
+ var progress = new Progress<double>();
- ((TaskManager)_taskManager).OnTaskExecuting(this);
+ CurrentCancellationTokenSource = new CancellationTokenSource();
- progress.ProgressChanged += OnProgressChanged;
+ _logger.LogDebug("Executing {0}", Name);
- TaskCompletionStatus status;
- CurrentExecutionStartTime = DateTime.UtcNow;
+ ((TaskManager)_taskManager).OnTaskExecuting(this);
- Exception failureException = null;
+ progress.ProgressChanged += OnProgressChanged;
- try
- {
- if (options is not null && options.MaxRuntimeTicks.HasValue)
- {
- CurrentCancellationTokenSource.CancelAfter(TimeSpan.FromTicks(options.MaxRuntimeTicks.Value));
- }
+ TaskCompletionStatus status;
+ CurrentExecutionStartTime = DateTime.UtcNow;
- await ScheduledTask.ExecuteAsync(progress, CurrentCancellationTokenSource.Token).ConfigureAwait(false);
+ Exception failureException = null;
- status = TaskCompletionStatus.Completed;
- }
- catch (OperationCanceledException)
+ try
+ {
+ if (options is not null && options.MaxRuntimeTicks.HasValue)
{
- status = TaskCompletionStatus.Cancelled;
+ CurrentCancellationTokenSource.CancelAfter(TimeSpan.FromTicks(options.MaxRuntimeTicks.Value));
}
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error executing Scheduled Task");
- failureException = ex;
-
- status = TaskCompletionStatus.Failed;
- }
+ await ScheduledTask.ExecuteAsync(progress, CurrentCancellationTokenSource.Token).ConfigureAwait(false);
- var startTime = CurrentExecutionStartTime;
- var endTime = DateTime.UtcNow;
+ status = TaskCompletionStatus.Completed;
+ }
+ catch (OperationCanceledException)
+ {
+ status = TaskCompletionStatus.Cancelled;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error executing Scheduled Task");
- progress.ProgressChanged -= OnProgressChanged;
- CurrentCancellationTokenSource.Dispose();
- CurrentCancellationTokenSource = null;
- CurrentProgress = null;
+ failureException = ex;
- OnTaskCompleted(startTime, endTime, status, failureException);
+ status = TaskCompletionStatus.Failed;
}
- /// <summary>
- /// Progress_s the progress changed.
- /// </summary>
- /// <param name="sender">The sender.</param>
- /// <param name="e">The e.</param>
- private void OnProgressChanged(object sender, double e)
- {
- e = Math.Min(e, 100);
+ var startTime = CurrentExecutionStartTime;
+ var endTime = DateTime.UtcNow;
- CurrentProgress = e;
+ progress.ProgressChanged -= OnProgressChanged;
+ CurrentCancellationTokenSource.Dispose();
+ CurrentCancellationTokenSource = null;
+ CurrentProgress = null;
- TaskProgress?.Invoke(this, new GenericEventArgs<double>(e));
- }
+ OnTaskCompleted(startTime, endTime, status, failureException);
+ }
- /// <summary>
- /// Stops the task if it is currently executing.
- /// </summary>
- /// <exception cref="InvalidOperationException">Cannot cancel a Task unless it is in the Running state.</exception>
- public void Cancel()
- {
- if (State != TaskState.Running)
- {
- throw new InvalidOperationException("Cannot cancel a Task unless it is in the Running state.");
- }
+ /// <summary>
+ /// Progress_s the progress changed.
+ /// </summary>
+ /// <param name="sender">The sender.</param>
+ /// <param name="e">The e.</param>
+ private void OnProgressChanged(object sender, double e)
+ {
+ e = Math.Min(e, 100);
- CancelIfRunning();
- }
+ CurrentProgress = e;
- /// <summary>
- /// Cancels if running.
- /// </summary>
- public void CancelIfRunning()
- {
- if (State == TaskState.Running)
- {
- _logger.LogInformation("Attempting to cancel Scheduled Task {0}", Name);
- CurrentCancellationTokenSource.Cancel();
- }
- }
+ TaskProgress?.Invoke(this, new GenericEventArgs<double>(e));
+ }
- /// <summary>
- /// Gets the scheduled tasks configuration directory.
- /// </summary>
- /// <returns>System.String.</returns>
- private string GetScheduledTasksConfigurationDirectory()
+ /// <summary>
+ /// Stops the task if it is currently executing.
+ /// </summary>
+ /// <exception cref="InvalidOperationException">Cannot cancel a Task unless it is in the Running state.</exception>
+ public void Cancel()
+ {
+ if (State != TaskState.Running)
{
- return Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "ScheduledTasks");
+ throw new InvalidOperationException("Cannot cancel a Task unless it is in the Running state.");
}
- /// <summary>
- /// Gets the scheduled tasks data directory.
- /// </summary>
- /// <returns>System.String.</returns>
- private string GetScheduledTasksDataDirectory()
- {
- return Path.Combine(_applicationPaths.DataPath, "ScheduledTasks");
- }
+ CancelIfRunning();
+ }
- /// <summary>
- /// Gets the history file path.
- /// </summary>
- /// <value>The history file path.</value>
- private string GetHistoryFilePath()
+ /// <summary>
+ /// Cancels if running.
+ /// </summary>
+ public void CancelIfRunning()
+ {
+ if (State == TaskState.Running)
{
- return Path.Combine(GetScheduledTasksDataDirectory(), new Guid(Id) + ".js");
+ _logger.LogInformation("Attempting to cancel Scheduled Task {0}", Name);
+ CurrentCancellationTokenSource.Cancel();
}
+ }
- /// <summary>
- /// Gets the configuration file path.
- /// </summary>
- /// <returns>System.String.</returns>
- private string GetConfigurationFilePath()
- {
- return Path.Combine(GetScheduledTasksConfigurationDirectory(), new Guid(Id) + ".js");
- }
+ /// <summary>
+ /// Gets the scheduled tasks configuration directory.
+ /// </summary>
+ /// <returns>System.String.</returns>
+ private string GetScheduledTasksConfigurationDirectory()
+ {
+ return Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "ScheduledTasks");
+ }
- /// <summary>
- /// Loads the triggers.
- /// </summary>
- /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
- private Tuple<TaskTriggerInfo, ITaskTrigger>[] LoadTriggers()
- {
- // This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
- var settings = LoadTriggerSettings().Where(i => i is not null);
+ /// <summary>
+ /// Gets the scheduled tasks data directory.
+ /// </summary>
+ /// <returns>System.String.</returns>
+ private string GetScheduledTasksDataDirectory()
+ {
+ return Path.Combine(_applicationPaths.DataPath, "ScheduledTasks");
+ }
- return settings.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray();
- }
+ /// <summary>
+ /// Gets the history file path.
+ /// </summary>
+ /// <value>The history file path.</value>
+ private string GetHistoryFilePath()
+ {
+ return Path.Combine(GetScheduledTasksDataDirectory(), new Guid(Id) + ".js");
+ }
- private TaskTriggerInfo[] LoadTriggerSettings()
- {
- string path = GetConfigurationFilePath();
- TaskTriggerInfo[] list = null;
- if (File.Exists(path))
- {
- var bytes = File.ReadAllBytes(path);
- list = JsonSerializer.Deserialize<TaskTriggerInfo[]>(bytes, _jsonOptions);
- }
+ /// <summary>
+ /// Gets the configuration file path.
+ /// </summary>
+ /// <returns>System.String.</returns>
+ private string GetConfigurationFilePath()
+ {
+ return Path.Combine(GetScheduledTasksConfigurationDirectory(), new Guid(Id) + ".js");
+ }
- // Return defaults if file doesn't exist.
- return list ?? GetDefaultTriggers();
- }
+ /// <summary>
+ /// Loads the triggers.
+ /// </summary>
+ /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
+ private Tuple<TaskTriggerInfo, ITaskTrigger>[] LoadTriggers()
+ {
+ // This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
+ var settings = LoadTriggerSettings().Where(i => i is not null);
+
+ return settings.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray();
+ }
- private TaskTriggerInfo[] GetDefaultTriggers()
+ private TaskTriggerInfo[] LoadTriggerSettings()
+ {
+ string path = GetConfigurationFilePath();
+ TaskTriggerInfo[] list = null;
+ if (File.Exists(path))
{
- try
- {
- return ScheduledTask.GetDefaultTriggers().ToArray();
- }
- catch
- {
- return
- [
- new()
- {
- IntervalTicks = TimeSpan.FromDays(1).Ticks,
- Type = TaskTriggerInfoType.IntervalTrigger
- }
- ];
- }
+ var bytes = File.ReadAllBytes(path);
+ list = JsonSerializer.Deserialize<TaskTriggerInfo[]>(bytes, _jsonOptions);
}
- /// <summary>
- /// Saves the triggers.
- /// </summary>
- /// <param name="triggers">The triggers.</param>
- private void SaveTriggers(TaskTriggerInfo[] triggers)
- {
- var path = GetConfigurationFilePath();
+ // Return defaults if file doesn't exist.
+ return list ?? GetDefaultTriggers();
+ }
- Directory.CreateDirectory(Path.GetDirectoryName(path));
- using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
- using Utf8JsonWriter jsonWriter = new Utf8JsonWriter(createStream);
- JsonSerializer.Serialize(jsonWriter, triggers, _jsonOptions);
+ private TaskTriggerInfo[] GetDefaultTriggers()
+ {
+ try
+ {
+ return ScheduledTask.GetDefaultTriggers().ToArray();
}
-
- /// <summary>
- /// Called when [task completed].
- /// </summary>
- /// <param name="startTime">The start time.</param>
- /// <param name="endTime">The end time.</param>
- /// <param name="status">The status.</param>
- /// <param name="ex">The exception.</param>
- private void OnTaskCompleted(DateTime startTime, DateTime endTime, TaskCompletionStatus status, Exception ex)
+ catch
{
- var elapsedTime = endTime - startTime;
+ return
+ [
+ new()
+ {
+ IntervalTicks = TimeSpan.FromDays(1).Ticks,
+ Type = TaskTriggerInfoType.IntervalTrigger
+ }
+ ];
+ }
+ }
- _logger.LogInformation("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds);
+ /// <summary>
+ /// Saves the triggers.
+ /// </summary>
+ /// <param name="triggers">The triggers.</param>
+ private void SaveTriggers(TaskTriggerInfo[] triggers)
+ {
+ var path = GetConfigurationFilePath();
- var result = new TaskResult
- {
- StartTimeUtc = startTime,
- EndTimeUtc = endTime,
- Status = status,
- Name = Name,
- Id = Id
- };
+ Directory.CreateDirectory(Path.GetDirectoryName(path));
+ using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
+ using Utf8JsonWriter jsonWriter = new Utf8JsonWriter(createStream);
+ JsonSerializer.Serialize(jsonWriter, triggers, _jsonOptions);
+ }
- result.Key = ScheduledTask.Key;
+ /// <summary>
+ /// Called when [task completed].
+ /// </summary>
+ /// <param name="startTime">The start time.</param>
+ /// <param name="endTime">The end time.</param>
+ /// <param name="status">The status.</param>
+ /// <param name="ex">The exception.</param>
+ private void OnTaskCompleted(DateTime startTime, DateTime endTime, TaskCompletionStatus status, Exception ex)
+ {
+ var elapsedTime = endTime - startTime;
- if (ex is not null)
- {
- result.ErrorMessage = ex.Message;
- result.LongErrorMessage = ex.StackTrace;
- }
+ _logger.LogInformation("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds);
- LastExecutionResult = result;
+ var result = new TaskResult
+ {
+ StartTimeUtc = startTime,
+ EndTimeUtc = endTime,
+ Status = status,
+ Name = Name,
+ Id = Id
+ };
- ((TaskManager)_taskManager).OnTaskCompleted(this, result);
- }
+ result.Key = ScheduledTask.Key;
- /// <inheritdoc />
- public void Dispose()
+ if (ex is not null)
{
- Dispose(true);
- GC.SuppressFinalize(this);
+ result.ErrorMessage = ex.Message;
+ result.LongErrorMessage = ex.StackTrace;
}
- /// <summary>
- /// Releases unmanaged and - optionally - managed resources.
- /// </summary>
- /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
- protected virtual void Dispose(bool dispose)
+ LastExecutionResult = result;
+
+ ((TaskManager)_taskManager).OnTaskCompleted(this, result);
+ }
+
+ /// <inheritdoc />
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Releases unmanaged and - optionally - managed resources.
+ /// </summary>
+ /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
+ protected virtual void Dispose(bool dispose)
+ {
+ if (dispose)
{
- if (dispose)
- {
- DisposeTriggers();
+ DisposeTriggers();
- var wasRunning = State == TaskState.Running;
- var startTime = CurrentExecutionStartTime;
+ var wasRunning = State == TaskState.Running;
+ var startTime = CurrentExecutionStartTime;
- var token = CurrentCancellationTokenSource;
- if (token is not null)
+ var token = CurrentCancellationTokenSource;
+ if (token is not null)
+ {
+ try
{
- try
- {
- _logger.LogInformation("{Name}: Cancelling", Name);
- token.Cancel();
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error calling CancellationToken.Cancel();");
- }
+ _logger.LogInformation("{Name}: Cancelling", Name);
+ token.Cancel();
}
-
- var task = _currentTask;
- if (task is not null)
+ catch (Exception ex)
{
- try
- {
- _logger.LogInformation("{Name}: Waiting on Task", Name);
- var exited = task.Wait(2000);
-
- if (exited)
- {
- _logger.LogInformation("{Name}: Task exited", Name);
- }
- else
- {
- _logger.LogInformation("{Name}: Timed out waiting for task to stop", Name);
- }
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error calling Task.WaitAll();");
- }
+ _logger.LogError(ex, "Error calling CancellationToken.Cancel();");
}
+ }
- if (token is not null)
+ var task = _currentTask;
+ if (task is not null)
+ {
+ try
{
- try
+ _logger.LogInformation("{Name}: Waiting on Task", Name);
+ var exited = task.Wait(2000);
+
+ if (exited)
{
- _logger.LogDebug("{Name}: Disposing CancellationToken", Name);
- token.Dispose();
+ _logger.LogInformation("{Name}: Task exited", Name);
}
- catch (Exception ex)
+ else
{
- _logger.LogError(ex, "Error calling CancellationToken.Dispose();");
+ _logger.LogInformation("{Name}: Timed out waiting for task to stop", Name);
}
}
-
- if (wasRunning)
+ catch (Exception ex)
{
- OnTaskCompleted(startTime, DateTime.UtcNow, TaskCompletionStatus.Aborted, null);
+ _logger.LogError(ex, "Error calling Task.WaitAll();");
}
}
- }
-
- /// <summary>
- /// Converts a TaskTriggerInfo into a concrete BaseTaskTrigger.
- /// </summary>
- /// <param name="info">The info.</param>
- /// <returns>BaseTaskTrigger.</returns>
- /// <exception cref="ArgumentException">Invalid trigger type: + info.Type.</exception>
- private ITaskTrigger GetTrigger(TaskTriggerInfo info)
- {
- var options = new TaskOptions
- {
- MaxRuntimeTicks = info.MaxRuntimeTicks
- };
- if (info.Type == TaskTriggerInfoType.DailyTrigger)
+ if (token is not null)
{
- if (!info.TimeOfDayTicks.HasValue)
+ try
{
- throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
+ _logger.LogDebug("{Name}: Disposing CancellationToken", Name);
+ token.Dispose();
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error calling CancellationToken.Dispose();");
}
-
- return new DailyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), options);
}
- if (info.Type == TaskTriggerInfoType.WeeklyTrigger)
+ if (wasRunning)
{
- if (!info.TimeOfDayTicks.HasValue)
- {
- throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
- }
+ OnTaskCompleted(startTime, DateTime.UtcNow, TaskCompletionStatus.Aborted, null);
+ }
+ }
+ }
- if (!info.DayOfWeek.HasValue)
- {
- throw new ArgumentException("Info did not contain a DayOfWeek.", nameof(info));
- }
+ /// <summary>
+ /// Converts a TaskTriggerInfo into a concrete BaseTaskTrigger.
+ /// </summary>
+ /// <param name="info">The info.</param>
+ /// <returns>BaseTaskTrigger.</returns>
+ /// <exception cref="ArgumentException">Invalid trigger type: + info.Type.</exception>
+ private ITaskTrigger GetTrigger(TaskTriggerInfo info)
+ {
+ var options = new TaskOptions
+ {
+ MaxRuntimeTicks = info.MaxRuntimeTicks
+ };
- return new WeeklyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), info.DayOfWeek.Value, options);
+ if (info.Type == TaskTriggerInfoType.DailyTrigger)
+ {
+ if (!info.TimeOfDayTicks.HasValue)
+ {
+ throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
}
- if (info.Type == TaskTriggerInfoType.IntervalTrigger)
+ return new DailyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), options);
+ }
+
+ if (info.Type == TaskTriggerInfoType.WeeklyTrigger)
+ {
+ if (!info.TimeOfDayTicks.HasValue)
{
- if (!info.IntervalTicks.HasValue)
- {
- throw new ArgumentException("Info did not contain a IntervalTicks.", nameof(info));
- }
+ throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
+ }
- return new IntervalTrigger(TimeSpan.FromTicks(info.IntervalTicks.Value), options);
+ if (!info.DayOfWeek.HasValue)
+ {
+ throw new ArgumentException("Info did not contain a DayOfWeek.", nameof(info));
}
- if (info.Type == TaskTriggerInfoType.StartupTrigger)
+ return new WeeklyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), info.DayOfWeek.Value, options);
+ }
+
+ if (info.Type == TaskTriggerInfoType.IntervalTrigger)
+ {
+ if (!info.IntervalTicks.HasValue)
{
- return new StartupTrigger(options);
+ throw new ArgumentException("Info did not contain a IntervalTicks.", nameof(info));
}
- throw new ArgumentException("Unrecognized trigger type: " + info.Type);
+ return new IntervalTrigger(TimeSpan.FromTicks(info.IntervalTicks.Value), options);
}
- /// <summary>
- /// Disposes each trigger.
- /// </summary>
- private void DisposeTriggers()
+ if (info.Type == TaskTriggerInfoType.StartupTrigger)
{
- foreach (var triggerInfo in InternalTriggers)
+ return new StartupTrigger(options);
+ }
+
+ throw new ArgumentException("Unrecognized trigger type: " + info.Type);
+ }
+
+ /// <summary>
+ /// Disposes each trigger.
+ /// </summary>
+ private void DisposeTriggers()
+ {
+ foreach (var triggerInfo in InternalTriggers)
+ {
+ var trigger = triggerInfo.Item2;
+ trigger.Triggered -= OnTriggerTriggered;
+ trigger.Stop();
+ if (trigger is IDisposable disposable)
{
- var trigger = triggerInfo.Item2;
- trigger.Triggered -= OnTriggerTriggered;
- trigger.Stop();
- if (trigger is IDisposable disposable)
- {
- disposable.Dispose();
- }
+ disposable.Dispose();
}
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs
index a5e4104ff..4ec2c9c78 100644
--- a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs
@@ -8,255 +8,254 @@ using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.ScheduledTasks
+namespace Emby.Server.Implementations.ScheduledTasks;
+
+/// <summary>
+/// Class TaskManager.
+/// </summary>
+public class TaskManager : ITaskManager
{
/// <summary>
- /// Class TaskManager.
+ /// The _task queue.
/// </summary>
- public class TaskManager : ITaskManager
- {
- /// <summary>
- /// The _task queue.
- /// </summary>
- private readonly ConcurrentQueue<Tuple<Type, TaskOptions>> _taskQueue =
- new ConcurrentQueue<Tuple<Type, TaskOptions>>();
-
- private readonly IApplicationPaths _applicationPaths;
- private readonly ILogger<TaskManager> _logger;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="TaskManager" /> class.
- /// </summary>
- /// <param name="applicationPaths">The application paths.</param>
- /// <param name="logger">The logger.</param>
- public TaskManager(
- IApplicationPaths applicationPaths,
- ILogger<TaskManager> logger)
- {
- _applicationPaths = applicationPaths;
- _logger = logger;
+ private readonly ConcurrentQueue<Tuple<Type, TaskOptions>> _taskQueue =
+ new ConcurrentQueue<Tuple<Type, TaskOptions>>();
- ScheduledTasks = Array.Empty<IScheduledTaskWorker>();
- }
+ private readonly IApplicationPaths _applicationPaths;
+ private readonly ILogger<TaskManager> _logger;
- /// <inheritdoc />
- public event EventHandler<GenericEventArgs<IScheduledTaskWorker>>? TaskExecuting;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TaskManager" /> class.
+ /// </summary>
+ /// <param name="applicationPaths">The application paths.</param>
+ /// <param name="logger">The logger.</param>
+ public TaskManager(
+ IApplicationPaths applicationPaths,
+ ILogger<TaskManager> logger)
+ {
+ _applicationPaths = applicationPaths;
+ _logger = logger;
- /// <inheritdoc />
- public event EventHandler<TaskCompletionEventArgs>? TaskCompleted;
+ ScheduledTasks = [];
+ }
- /// <inheritdoc />
- public IReadOnlyList<IScheduledTaskWorker> ScheduledTasks { get; private set; }
+ /// <inheritdoc />
+ public event EventHandler<GenericEventArgs<IScheduledTaskWorker>>? TaskExecuting;
- /// <inheritdoc />
- public void CancelIfRunningAndQueue<T>(TaskOptions options)
- where T : IScheduledTask
- {
- var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
- ((ScheduledTaskWorker)task).CancelIfRunning();
+ /// <inheritdoc />
+ public event EventHandler<TaskCompletionEventArgs>? TaskCompleted;
- QueueScheduledTask<T>(options);
- }
+ /// <inheritdoc />
+ public IReadOnlyList<IScheduledTaskWorker> ScheduledTasks { get; private set; }
- /// <inheritdoc />
- public void CancelIfRunningAndQueue<T>()
- where T : IScheduledTask
- {
- CancelIfRunningAndQueue<T>(new TaskOptions());
- }
+ /// <inheritdoc />
+ public void CancelIfRunningAndQueue<T>(TaskOptions options)
+ where T : IScheduledTask
+ {
+ var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
+ ((ScheduledTaskWorker)task).CancelIfRunning();
- /// <inheritdoc />
- public void CancelIfRunning<T>()
- where T : IScheduledTask
- {
- var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
- ((ScheduledTaskWorker)task).CancelIfRunning();
- }
+ QueueScheduledTask<T>(options);
+ }
- /// <inheritdoc />
- public void QueueScheduledTask<T>(TaskOptions options)
+ /// <inheritdoc />
+ public void CancelIfRunningAndQueue<T>()
where T : IScheduledTask
- {
- var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T));
+ {
+ CancelIfRunningAndQueue<T>(new TaskOptions());
+ }
- if (scheduledTask is null)
- {
- _logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", typeof(T).Name);
- }
- else
- {
- QueueScheduledTask(scheduledTask, options);
- }
- }
+ /// <inheritdoc />
+ public void CancelIfRunning<T>()
+ where T : IScheduledTask
+ {
+ var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
+ ((ScheduledTaskWorker)task).CancelIfRunning();
+ }
- /// <inheritdoc />
- public void QueueScheduledTask<T>()
- where T : IScheduledTask
- {
- QueueScheduledTask<T>(new TaskOptions());
- }
+ /// <inheritdoc />
+ public void QueueScheduledTask<T>(TaskOptions options)
+ where T : IScheduledTask
+ {
+ var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T));
- /// <inheritdoc />
- public void QueueIfNotRunning<T>()
- where T : IScheduledTask
+ if (scheduledTask is null)
{
- var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
-
- if (task.State != TaskState.Running)
- {
- QueueScheduledTask<T>(new TaskOptions());
- }
+ _logger.LogError("Unable to find scheduled task of type {Type} in QueueScheduledTask.", typeof(T).Name);
}
-
- /// <inheritdoc />
- public void Execute<T>()
- where T : IScheduledTask
+ else
{
- var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T));
+ QueueScheduledTask(scheduledTask, options);
+ }
+ }
- if (scheduledTask is null)
- {
- _logger.LogError("Unable to find scheduled task of type {0} in Execute.", typeof(T).Name);
- }
- else
- {
- var type = scheduledTask.ScheduledTask.GetType();
+ /// <inheritdoc />
+ public void QueueScheduledTask<T>()
+ where T : IScheduledTask
+ {
+ QueueScheduledTask<T>(new TaskOptions());
+ }
- _logger.LogDebug("Queuing task {0}", type.Name);
+ /// <inheritdoc />
+ public void QueueIfNotRunning<T>()
+ where T : IScheduledTask
+ {
+ var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));
- lock (_taskQueue)
- {
- if (scheduledTask.State == TaskState.Idle)
- {
- Execute(scheduledTask, new TaskOptions());
- }
- }
- }
+ if (task.State != TaskState.Running)
+ {
+ QueueScheduledTask<T>(new TaskOptions());
}
+ }
- /// <inheritdoc />
- public void QueueScheduledTask(IScheduledTask task, TaskOptions options)
- {
- var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == task.GetType());
+ /// <inheritdoc />
+ public void Execute<T>()
+ where T : IScheduledTask
+ {
+ var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T));
- if (scheduledTask is null)
- {
- _logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name);
- }
- else
- {
- QueueScheduledTask(scheduledTask, options);
- }
+ if (scheduledTask is null)
+ {
+ _logger.LogError("Unable to find scheduled task of type {Type} in Execute.", typeof(T).Name);
}
-
- /// <summary>
- /// Queues the scheduled task.
- /// </summary>
- /// <param name="task">The task.</param>
- /// <param name="options">The task options.</param>
- private void QueueScheduledTask(IScheduledTaskWorker task, TaskOptions options)
+ else
{
- var type = task.ScheduledTask.GetType();
+ var type = scheduledTask.ScheduledTask.GetType();
- _logger.LogDebug("Queuing task {0}", type.Name);
+ _logger.LogDebug("Queuing task {Name}", type.Name);
lock (_taskQueue)
{
- if (task.State == TaskState.Idle)
+ if (scheduledTask.State == TaskState.Idle)
{
- Execute(task, options);
- return;
+ Execute(scheduledTask, new TaskOptions());
}
-
- _taskQueue.Enqueue(new Tuple<Type, TaskOptions>(type, options));
}
}
+ }
- /// <inheritdoc />
- public void AddTasks(IEnumerable<IScheduledTask> tasks)
- {
- var list = tasks.Select(t => new ScheduledTaskWorker(t, _applicationPaths, this, _logger));
+ /// <inheritdoc />
+ public void QueueScheduledTask(IScheduledTask task, TaskOptions options)
+ {
+ var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == task.GetType());
- ScheduledTasks = ScheduledTasks.Concat(list).ToArray();
+ if (scheduledTask is null)
+ {
+ _logger.LogError("Unable to find scheduled task of type {Type} in QueueScheduledTask.", task.GetType().Name);
}
-
- /// <inheritdoc />
- public void Dispose()
+ else
{
- Dispose(true);
- GC.SuppressFinalize(this);
+ QueueScheduledTask(scheduledTask, options);
}
+ }
+
+ /// <summary>
+ /// Queues the scheduled task.
+ /// </summary>
+ /// <param name="task">The task.</param>
+ /// <param name="options">The task options.</param>
+ private void QueueScheduledTask(IScheduledTaskWorker task, TaskOptions options)
+ {
+ var type = task.ScheduledTask.GetType();
+
+ _logger.LogDebug("Queuing task {Name}", type.Name);
- /// <summary>
- /// Releases unmanaged and - optionally - managed resources.
- /// </summary>
- /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
- protected virtual void Dispose(bool dispose)
+ lock (_taskQueue)
{
- foreach (var task in ScheduledTasks)
+ if (task.State == TaskState.Idle)
{
- task.Dispose();
+ Execute(task, options);
+ return;
}
- }
- /// <inheritdoc />
- public void Cancel(IScheduledTaskWorker task)
- {
- ((ScheduledTaskWorker)task).Cancel();
+ _taskQueue.Enqueue(new Tuple<Type, TaskOptions>(type, options));
}
+ }
- /// <inheritdoc />
- public Task Execute(IScheduledTaskWorker task, TaskOptions options)
- {
- return ((ScheduledTaskWorker)task).Execute(options);
- }
+ /// <inheritdoc />
+ public void AddTasks(IEnumerable<IScheduledTask> tasks)
+ {
+ var list = tasks.Select(t => new ScheduledTaskWorker(t, _applicationPaths, this, _logger));
+
+ ScheduledTasks = ScheduledTasks.Concat(list).ToArray();
+ }
+
+ /// <inheritdoc />
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
- /// <summary>
- /// Called when [task executing].
- /// </summary>
- /// <param name="task">The task.</param>
- internal void OnTaskExecuting(IScheduledTaskWorker task)
+ /// <summary>
+ /// Releases unmanaged and - optionally - managed resources.
+ /// </summary>
+ /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
+ protected virtual void Dispose(bool dispose)
+ {
+ foreach (var task in ScheduledTasks)
{
- TaskExecuting?.Invoke(this, new GenericEventArgs<IScheduledTaskWorker>(task));
+ task.Dispose();
}
+ }
- /// <summary>
- /// Called when [task completed].
- /// </summary>
- /// <param name="task">The task.</param>
- /// <param name="result">The result.</param>
- internal void OnTaskCompleted(IScheduledTaskWorker task, TaskResult result)
- {
- TaskCompleted?.Invoke(task, new TaskCompletionEventArgs(task, result));
+ /// <inheritdoc />
+ public void Cancel(IScheduledTaskWorker task)
+ {
+ ((ScheduledTaskWorker)task).Cancel();
+ }
- ExecuteQueuedTasks();
- }
+ /// <inheritdoc />
+ public Task Execute(IScheduledTaskWorker task, TaskOptions options)
+ {
+ return ((ScheduledTaskWorker)task).Execute(options);
+ }
+
+ /// <summary>
+ /// Called when [task executing].
+ /// </summary>
+ /// <param name="task">The task.</param>
+ internal void OnTaskExecuting(IScheduledTaskWorker task)
+ {
+ TaskExecuting?.Invoke(this, new GenericEventArgs<IScheduledTaskWorker>(task));
+ }
+
+ /// <summary>
+ /// Called when [task completed].
+ /// </summary>
+ /// <param name="task">The task.</param>
+ /// <param name="result">The result.</param>
+ internal void OnTaskCompleted(IScheduledTaskWorker task, TaskResult result)
+ {
+ TaskCompleted?.Invoke(task, new TaskCompletionEventArgs(task, result));
+
+ ExecuteQueuedTasks();
+ }
- /// <summary>
- /// Executes the queued tasks.
- /// </summary>
- private void ExecuteQueuedTasks()
+ /// <summary>
+ /// Executes the queued tasks.
+ /// </summary>
+ private void ExecuteQueuedTasks()
+ {
+ lock (_taskQueue)
{
- lock (_taskQueue)
- {
- var list = new List<Tuple<Type, TaskOptions>>();
+ var list = new List<Tuple<Type, TaskOptions>>();
- while (_taskQueue.TryDequeue(out var item))
+ while (_taskQueue.TryDequeue(out var item))
+ {
+ if (list.All(i => i.Item1 != item.Item1))
{
- if (list.All(i => i.Item1 != item.Item1))
- {
- list.Add(item);
- }
+ list.Add(item);
}
+ }
- foreach (var enqueuedType in list)
- {
- var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == enqueuedType.Item1);
+ foreach (var enqueuedType in list)
+ {
+ var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == enqueuedType.Item1);
- if (scheduledTask.State == TaskState.Idle)
- {
- Execute(scheduledTask, enqueuedType.Item2);
- }
+ if (scheduledTask.State == TaskState.Idle)
+ {
+ Execute(scheduledTask, enqueuedType.Item2);
}
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/AudioNormalizationTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/AudioNormalizationTask.cs
index 8d1d509ff..ef005bfaa 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/AudioNormalizationTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/AudioNormalizationTask.cs
@@ -156,14 +156,11 @@ public partial class AudioNormalizationTask : IScheduledTask
/// <inheritdoc />
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
- return
- [
- new TaskTriggerInfo
- {
- Type = TaskTriggerInfoType.IntervalTrigger,
- IntervalTicks = TimeSpan.FromHours(24).Ticks
- }
- ];
+ yield return new TaskTriggerInfo
+ {
+ Type = TaskTriggerInfoType.IntervalTrigger,
+ IntervalTicks = TimeSpan.FromHours(24).Ticks
+ };
}
private async Task<float?> CalculateLUFSAsync(string inputArgs, bool waitForExit, CancellationToken cancellationToken)
@@ -194,7 +191,7 @@ public partial class AudioNormalizationTask : IScheduledTask
using var reader = process.StandardError;
float? lufs = null;
- await foreach (var line in reader.ReadAllLinesAsync(cancellationToken))
+ await foreach (var line in reader.ReadAllLinesAsync(cancellationToken).ConfigureAwait(false))
{
Match match = LUFSRegex().Match(line);
if (match.Success)
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs
index 563e90fbe..f81309560 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs
@@ -11,171 +11,157 @@ using MediaBrowser.Controller.Chapters;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.MediaEncoding;
-using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.ScheduledTasks.Tasks
+namespace Emby.Server.Implementations.ScheduledTasks.Tasks;
+
+/// <summary>
+/// Class ChapterImagesTask.
+/// </summary>
+public class ChapterImagesTask : IScheduledTask
{
+ private readonly ILogger<ChapterImagesTask> _logger;
+ private readonly ILibraryManager _libraryManager;
+ private readonly IApplicationPaths _appPaths;
+ private readonly IChapterManager _chapterManager;
+ private readonly IFileSystem _fileSystem;
+ private readonly ILocalizationManager _localization;
+
/// <summary>
- /// Class ChapterImagesTask.
+ /// Initializes a new instance of the <see cref="ChapterImagesTask" /> class.
/// </summary>
- public class ChapterImagesTask : IScheduledTask
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="appPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
+ /// <param name="chapterManager">Instance of the <see cref="IChapterManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
+ public ChapterImagesTask(
+ ILogger<ChapterImagesTask> logger,
+ ILibraryManager libraryManager,
+ IApplicationPaths appPaths,
+ IChapterManager chapterManager,
+ IFileSystem fileSystem,
+ ILocalizationManager localization)
{
- private readonly ILogger<ChapterImagesTask> _logger;
- private readonly ILibraryManager _libraryManager;
- private readonly IItemRepository _itemRepo;
- private readonly IApplicationPaths _appPaths;
- private readonly IEncodingManager _encodingManager;
- private readonly IFileSystem _fileSystem;
- private readonly ILocalizationManager _localization;
- private readonly IChapterRepository _chapterRepository;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ChapterImagesTask" /> class.
- /// </summary>
- /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
- /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
- /// <param name="itemRepo">Instance of the <see cref="IItemRepository"/> interface.</param>
- /// <param name="appPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
- /// <param name="encodingManager">Instance of the <see cref="IEncodingManager"/> interface.</param>
- /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
- /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
- /// <param name="chapterRepository">Instance of the <see cref="IChapterRepository"/> interface.</param>
- public ChapterImagesTask(
- ILogger<ChapterImagesTask> logger,
- ILibraryManager libraryManager,
- IItemRepository itemRepo,
- IApplicationPaths appPaths,
- IEncodingManager encodingManager,
- IFileSystem fileSystem,
- ILocalizationManager localization,
- IChapterRepository chapterRepository)
- {
- _logger = logger;
- _libraryManager = libraryManager;
- _itemRepo = itemRepo;
- _appPaths = appPaths;
- _encodingManager = encodingManager;
- _fileSystem = fileSystem;
- _localization = localization;
- _chapterRepository = chapterRepository;
- }
+ _logger = logger;
+ _libraryManager = libraryManager;
+ _appPaths = appPaths;
+ _chapterManager = chapterManager;
+ _fileSystem = fileSystem;
+ _localization = localization;
+ }
- /// <inheritdoc />
- public string Name => _localization.GetLocalizedString("TaskRefreshChapterImages");
+ /// <inheritdoc />
+ public string Name => _localization.GetLocalizedString("TaskRefreshChapterImages");
- /// <inheritdoc />
- public string Description => _localization.GetLocalizedString("TaskRefreshChapterImagesDescription");
+ /// <inheritdoc />
+ public string Description => _localization.GetLocalizedString("TaskRefreshChapterImagesDescription");
- /// <inheritdoc />
- public string Category => _localization.GetLocalizedString("TasksLibraryCategory");
+ /// <inheritdoc />
+ public string Category => _localization.GetLocalizedString("TasksLibraryCategory");
- /// <inheritdoc />
- public string Key => "RefreshChapterImages";
+ /// <inheritdoc />
+ public string Key => "RefreshChapterImages";
- /// <inheritdoc />
- public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ /// <inheritdoc />
+ public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ {
+ yield return new TaskTriggerInfo
{
- return
- [
- new TaskTriggerInfo
- {
- Type = TaskTriggerInfoType.DailyTrigger,
- TimeOfDayTicks = TimeSpan.FromHours(2).Ticks,
- MaxRuntimeTicks = TimeSpan.FromHours(4).Ticks
- }
- ];
- }
+ Type = TaskTriggerInfoType.DailyTrigger,
+ TimeOfDayTicks = TimeSpan.FromHours(2).Ticks,
+ MaxRuntimeTicks = TimeSpan.FromHours(4).Ticks
+ };
+ }
- /// <inheritdoc />
- public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ var videos = _libraryManager.GetItemList(new InternalItemsQuery
{
- var videos = _libraryManager.GetItemList(new InternalItemsQuery
+ MediaTypes = [MediaType.Video],
+ IsFolder = false,
+ Recursive = true,
+ DtoOptions = new DtoOptions(false)
{
- MediaTypes = [MediaType.Video],
- IsFolder = false,
- Recursive = true,
- DtoOptions = new DtoOptions(false)
- {
- EnableImages = false
- },
- SourceTypes = [SourceType.Library],
- IsVirtualItem = false
- })
- .OfType<Video>()
- .ToList();
+ EnableImages = false
+ },
+ SourceTypes = [SourceType.Library],
+ IsVirtualItem = false
+ })
+ .OfType<Video>()
+ .ToList();
- var numComplete = 0;
+ var numComplete = 0;
- var failHistoryPath = Path.Combine(_appPaths.CachePath, "chapter-failures.txt");
+ var failHistoryPath = Path.Combine(_appPaths.CachePath, "chapter-failures.txt");
- List<string> previouslyFailedImages;
+ List<string> previouslyFailedImages;
- if (File.Exists(failHistoryPath))
+ if (File.Exists(failHistoryPath))
+ {
+ try
{
- try
- {
- previouslyFailedImages = (await File.ReadAllTextAsync(failHistoryPath, cancellationToken).ConfigureAwait(false))
- .Split('|', StringSplitOptions.RemoveEmptyEntries)
- .ToList();
- }
- catch (IOException)
- {
- previouslyFailedImages = new List<string>();
- }
+ previouslyFailedImages = (await File.ReadAllTextAsync(failHistoryPath, cancellationToken).ConfigureAwait(false))
+ .Split('|', StringSplitOptions.RemoveEmptyEntries)
+ .ToList();
}
- else
+ catch (IOException)
{
- previouslyFailedImages = new List<string>();
+ previouslyFailedImages = [];
}
+ }
+ else
+ {
+ previouslyFailedImages = [];
+ }
- var directoryService = new DirectoryService(_fileSystem);
-
- foreach (var video in videos)
- {
- cancellationToken.ThrowIfCancellationRequested();
+ var directoryService = new DirectoryService(_fileSystem);
- var key = video.Path + video.DateModified.Ticks;
+ foreach (var video in videos)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
- var extract = !previouslyFailedImages.Contains(key, StringComparison.OrdinalIgnoreCase);
+ var key = video.Path + video.DateModified.Ticks;
- try
- {
- var chapters = _chapterRepository.GetChapters(video.Id);
+ var extract = !previouslyFailedImages.Contains(key, StringComparison.OrdinalIgnoreCase);
- var success = await _encodingManager.RefreshChapterImages(video, directoryService, chapters, extract, true, cancellationToken).ConfigureAwait(false);
+ try
+ {
+ var chapters = _chapterManager.GetChapters(video.Id);
- if (!success)
- {
- previouslyFailedImages.Add(key);
+ var success = await _chapterManager.RefreshChapterImages(video, directoryService, chapters, extract, true, cancellationToken).ConfigureAwait(false);
- var parentPath = Path.GetDirectoryName(failHistoryPath);
- if (parentPath is not null)
- {
- Directory.CreateDirectory(parentPath);
- }
+ if (!success)
+ {
+ previouslyFailedImages.Add(key);
- string text = string.Join('|', previouslyFailedImages);
- await File.WriteAllTextAsync(failHistoryPath, text, cancellationToken).ConfigureAwait(false);
+ var parentPath = Path.GetDirectoryName(failHistoryPath);
+ if (parentPath is not null)
+ {
+ Directory.CreateDirectory(parentPath);
}
- numComplete++;
- double percent = numComplete;
- percent /= videos.Count;
-
- progress.Report(100 * percent);
- }
- catch (ObjectDisposedException ex)
- {
- // TODO Investigate and properly fix.
- _logger.LogError(ex, "Object Disposed");
- break;
+ string text = string.Join('|', previouslyFailedImages);
+ await File.WriteAllTextAsync(failHistoryPath, text, cancellationToken).ConfigureAwait(false);
}
+
+ numComplete++;
+ double percent = numComplete;
+ percent /= videos.Count;
+
+ progress.Report(100 * percent);
+ }
+ catch (ObjectDisposedException ex)
+ {
+ // TODO Investigate and properly fix.
+ _logger.LogError(ex, "Object Disposed");
+ break;
}
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs
index fe1832165..1621bbaa1 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs
@@ -7,71 +7,70 @@ using MediaBrowser.Model.Activity;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Tasks;
-namespace Emby.Server.Implementations.ScheduledTasks.Tasks
+namespace Emby.Server.Implementations.ScheduledTasks.Tasks;
+
+/// <summary>
+/// Deletes old activity log entries.
+/// </summary>
+public class CleanActivityLogTask : IScheduledTask, IConfigurableScheduledTask
{
+ private readonly ILocalizationManager _localization;
+ private readonly IActivityManager _activityManager;
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+
/// <summary>
- /// Deletes old activity log entries.
+ /// Initializes a new instance of the <see cref="CleanActivityLogTask"/> class.
/// </summary>
- public class CleanActivityLogTask : IScheduledTask, IConfigurableScheduledTask
+ /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
+ /// <param name="activityManager">Instance of the <see cref="IActivityManager"/> interface.</param>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ public CleanActivityLogTask(
+ ILocalizationManager localization,
+ IActivityManager activityManager,
+ IServerConfigurationManager serverConfigurationManager)
{
- private readonly ILocalizationManager _localization;
- private readonly IActivityManager _activityManager;
- private readonly IServerConfigurationManager _serverConfigurationManager;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CleanActivityLogTask"/> class.
- /// </summary>
- /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
- /// <param name="activityManager">Instance of the <see cref="IActivityManager"/> interface.</param>
- /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
- public CleanActivityLogTask(
- ILocalizationManager localization,
- IActivityManager activityManager,
- IServerConfigurationManager serverConfigurationManager)
- {
- _localization = localization;
- _activityManager = activityManager;
- _serverConfigurationManager = serverConfigurationManager;
- }
+ _localization = localization;
+ _activityManager = activityManager;
+ _serverConfigurationManager = serverConfigurationManager;
+ }
- /// <inheritdoc />
- public string Name => _localization.GetLocalizedString("TaskCleanActivityLog");
+ /// <inheritdoc />
+ public string Name => _localization.GetLocalizedString("TaskCleanActivityLog");
- /// <inheritdoc />
- public string Key => "CleanActivityLog";
+ /// <inheritdoc />
+ public string Key => "CleanActivityLog";
- /// <inheritdoc />
- public string Description => _localization.GetLocalizedString("TaskCleanActivityLogDescription");
+ /// <inheritdoc />
+ public string Description => _localization.GetLocalizedString("TaskCleanActivityLogDescription");
- /// <inheritdoc />
- public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
+ /// <inheritdoc />
+ public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
- /// <inheritdoc />
- public bool IsHidden => false;
+ /// <inheritdoc />
+ public bool IsHidden => false;
- /// <inheritdoc />
- public bool IsEnabled => true;
+ /// <inheritdoc />
+ public bool IsEnabled => true;
- /// <inheritdoc />
- public bool IsLogged => true;
+ /// <inheritdoc />
+ public bool IsLogged => true;
- /// <inheritdoc />
- public Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ var retentionDays = _serverConfigurationManager.Configuration.ActivityLogRetentionDays;
+ if (!retentionDays.HasValue || retentionDays < 0)
{
- var retentionDays = _serverConfigurationManager.Configuration.ActivityLogRetentionDays;
- if (!retentionDays.HasValue || retentionDays < 0)
- {
- throw new InvalidOperationException($"Activity Log Retention days must be at least 0. Currently: {retentionDays}");
- }
-
- var startDate = DateTime.UtcNow.AddDays(-retentionDays.Value);
- return _activityManager.CleanAsync(startDate);
+ throw new InvalidOperationException($"Activity Log Retention days must be at least 0. Currently: {retentionDays}");
}
- /// <inheritdoc />
- public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
- {
- return [];
- }
+ var startDate = DateTime.UtcNow.AddDays(-retentionDays.Value);
+ return _activityManager.CleanAsync(startDate);
+ }
+
+ /// <inheritdoc />
+ public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ {
+ return [];
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanupCollectionAndPlaylistPathsTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanupCollectionAndPlaylistPathsTask.cs
index 8901390aa..7f68f7701 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanupCollectionAndPlaylistPathsTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanupCollectionAndPlaylistPathsTask.cs
@@ -27,7 +27,6 @@ public class CleanupCollectionAndPlaylistPathsTask : IScheduledTask
private readonly IPlaylistManager _playlistManager;
private readonly ILogger<CleanupCollectionAndPlaylistPathsTask> _logger;
private readonly IProviderManager _providerManager;
- private readonly IFileSystem _fileSystem;
/// <summary>
/// Initializes a new instance of the <see cref="CleanupCollectionAndPlaylistPathsTask"/> class.
@@ -37,21 +36,18 @@ public class CleanupCollectionAndPlaylistPathsTask : IScheduledTask
/// <param name="playlistManager">Instance of the <see cref="IPlaylistManager"/> interface.</param>
/// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
/// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
- /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
public CleanupCollectionAndPlaylistPathsTask(
ILocalizationManager localization,
ICollectionManager collectionManager,
IPlaylistManager playlistManager,
ILogger<CleanupCollectionAndPlaylistPathsTask> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem)
+ IProviderManager providerManager)
{
_localization = localization;
_collectionManager = collectionManager;
_playlistManager = playlistManager;
_logger = logger;
_providerManager = providerManager;
- _fileSystem = fileSystem;
}
/// <inheritdoc />
@@ -135,6 +131,9 @@ public class CleanupCollectionAndPlaylistPathsTask : IScheduledTask
/// <inheritdoc />
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
- return [new TaskTriggerInfo() { Type = TaskTriggerInfoType.StartupTrigger }];
+ yield return new TaskTriggerInfo
+ {
+ Type = TaskTriggerInfoType.StartupTrigger,
+ };
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs
index ff295d9b7..0e77f0102 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs
@@ -11,134 +11,133 @@ using MediaBrowser.Model.IO;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.ScheduledTasks.Tasks
+namespace Emby.Server.Implementations.ScheduledTasks.Tasks;
+
+/// <summary>
+/// Deletes old cache files.
+/// </summary>
+public class DeleteCacheFileTask : IScheduledTask, IConfigurableScheduledTask
{
/// <summary>
- /// Deletes old cache files.
+ /// Gets or sets the application paths.
+ /// </summary>
+ /// <value>The application paths.</value>
+ private readonly IApplicationPaths _applicationPaths;
+ private readonly ILogger<DeleteCacheFileTask> _logger;
+ private readonly IFileSystem _fileSystem;
+ private readonly ILocalizationManager _localization;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DeleteCacheFileTask" /> class.
/// </summary>
- public class DeleteCacheFileTask : IScheduledTask, IConfigurableScheduledTask
+ /// <param name="appPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
+ public DeleteCacheFileTask(
+ IApplicationPaths appPaths,
+ ILogger<DeleteCacheFileTask> logger,
+ IFileSystem fileSystem,
+ ILocalizationManager localization)
{
- /// <summary>
- /// Gets or sets the application paths.
- /// </summary>
- /// <value>The application paths.</value>
- private readonly IApplicationPaths _applicationPaths;
- private readonly ILogger<DeleteCacheFileTask> _logger;
- private readonly IFileSystem _fileSystem;
- private readonly ILocalizationManager _localization;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="DeleteCacheFileTask" /> class.
- /// </summary>
- /// <param name="appPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
- /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
- /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
- /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
- public DeleteCacheFileTask(
- IApplicationPaths appPaths,
- ILogger<DeleteCacheFileTask> logger,
- IFileSystem fileSystem,
- ILocalizationManager localization)
- {
- _applicationPaths = appPaths;
- _logger = logger;
- _fileSystem = fileSystem;
- _localization = localization;
- }
+ _applicationPaths = appPaths;
+ _logger = logger;
+ _fileSystem = fileSystem;
+ _localization = localization;
+ }
- /// <inheritdoc />
- public string Name => _localization.GetLocalizedString("TaskCleanCache");
+ /// <inheritdoc />
+ public string Name => _localization.GetLocalizedString("TaskCleanCache");
- /// <inheritdoc />
- public string Description => _localization.GetLocalizedString("TaskCleanCacheDescription");
+ /// <inheritdoc />
+ public string Description => _localization.GetLocalizedString("TaskCleanCacheDescription");
- /// <inheritdoc />
- public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
+ /// <inheritdoc />
+ public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
- /// <inheritdoc />
- public string Key => "DeleteCacheFiles";
+ /// <inheritdoc />
+ public string Key => "DeleteCacheFiles";
- /// <inheritdoc />
- public bool IsHidden => false;
+ /// <inheritdoc />
+ public bool IsHidden => false;
- /// <inheritdoc />
- public bool IsEnabled => true;
+ /// <inheritdoc />
+ public bool IsEnabled => true;
- /// <inheritdoc />
- public bool IsLogged => true;
+ /// <inheritdoc />
+ public bool IsLogged => true;
- /// <inheritdoc />
- public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ /// <inheritdoc />
+ public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ {
+ yield return new TaskTriggerInfo
{
- return
- [
- // Every so often
- new TaskTriggerInfo { Type = TaskTriggerInfoType.IntervalTrigger, IntervalTicks = TimeSpan.FromHours(24).Ticks }
- ];
- }
+ Type = TaskTriggerInfoType.IntervalTrigger,
+ IntervalTicks = TimeSpan.FromHours(24).Ticks
+ };
+ }
- /// <inheritdoc />
- public Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
+ /// <inheritdoc />
+ public Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ var minDateModified = DateTime.UtcNow.AddDays(-30);
+
+ try
+ {
+ DeleteCacheFilesFromDirectory(_applicationPaths.CachePath, minDateModified, progress, cancellationToken);
+ }
+ catch (DirectoryNotFoundException)
{
- var minDateModified = DateTime.UtcNow.AddDays(-30);
-
- try
- {
- DeleteCacheFilesFromDirectory(_applicationPaths.CachePath, minDateModified, progress, cancellationToken);
- }
- catch (DirectoryNotFoundException)
- {
- // No biggie here. Nothing to delete
- }
-
- progress.Report(90);
-
- minDateModified = DateTime.UtcNow.AddDays(-1);
-
- try
- {
- DeleteCacheFilesFromDirectory(_applicationPaths.TempDirectory, minDateModified, progress, cancellationToken);
- }
- catch (DirectoryNotFoundException)
- {
- // No biggie here. Nothing to delete
- }
-
- return Task.CompletedTask;
+ // No biggie here. Nothing to delete
}
- /// <summary>
- /// Deletes the cache files from directory with a last write time less than a given date.
- /// </summary>
- /// <param name="directory">The directory.</param>
- /// <param name="minDateModified">The min date modified.</param>
- /// <param name="progress">The progress.</param>
- /// <param name="cancellationToken">The task cancellation token.</param>
- private void DeleteCacheFilesFromDirectory(string directory, DateTime minDateModified, IProgress<double> progress, CancellationToken cancellationToken)
+ progress.Report(90);
+
+ minDateModified = DateTime.UtcNow.AddDays(-1);
+
+ try
{
- var filesToDelete = _fileSystem.GetFiles(directory, true)
- .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified)
- .ToList();
+ DeleteCacheFilesFromDirectory(_applicationPaths.TempDirectory, minDateModified, progress, cancellationToken);
+ }
+ catch (DirectoryNotFoundException)
+ {
+ // No biggie here. Nothing to delete
+ }
- var index = 0;
+ return Task.CompletedTask;
+ }
- foreach (var file in filesToDelete)
- {
- double percent = index;
- percent /= filesToDelete.Count;
+ /// <summary>
+ /// Deletes the cache files from directory with a last write time less than a given date.
+ /// </summary>
+ /// <param name="directory">The directory.</param>
+ /// <param name="minDateModified">The min date modified.</param>
+ /// <param name="progress">The progress.</param>
+ /// <param name="cancellationToken">The task cancellation token.</param>
+ private void DeleteCacheFilesFromDirectory(string directory, DateTime minDateModified, IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ var filesToDelete = _fileSystem.GetFiles(directory, true)
+ .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified)
+ .ToList();
- progress.Report(100 * percent);
+ var index = 0;
- cancellationToken.ThrowIfCancellationRequested();
+ foreach (var file in filesToDelete)
+ {
+ double percent = index;
+ percent /= filesToDelete.Count;
- FileSystemHelper.DeleteFile(_fileSystem, file.FullName, _logger);
+ progress.Report(100 * percent);
- index++;
- }
+ cancellationToken.ThrowIfCancellationRequested();
- FileSystemHelper.DeleteEmptyFolders(_fileSystem, directory, _logger);
+ FileSystemHelper.DeleteFile(_fileSystem, file.FullName, _logger);
- progress.Report(100);
+ index++;
}
+
+ FileSystemHelper.DeleteEmptyFolders(_fileSystem, directory, _logger);
+
+ progress.Report(100);
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs
index a091c2bd9..699529527 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs
@@ -9,93 +9,93 @@ using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Tasks;
-namespace Emby.Server.Implementations.ScheduledTasks.Tasks
+namespace Emby.Server.Implementations.ScheduledTasks.Tasks;
+
+/// <summary>
+/// Deletes old log files.
+/// </summary>
+public class DeleteLogFileTask : IScheduledTask, IConfigurableScheduledTask
{
+ private readonly IConfigurationManager _configurationManager;
+ private readonly IFileSystem _fileSystem;
+ private readonly ILocalizationManager _localization;
+
/// <summary>
- /// Deletes old log files.
+ /// Initializes a new instance of the <see cref="DeleteLogFileTask" /> class.
/// </summary>
- public class DeleteLogFileTask : IScheduledTask, IConfigurableScheduledTask
+ /// <param name="configurationManager">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
+ public DeleteLogFileTask(IConfigurationManager configurationManager, IFileSystem fileSystem, ILocalizationManager localization)
{
- private readonly IConfigurationManager _configurationManager;
- private readonly IFileSystem _fileSystem;
- private readonly ILocalizationManager _localization;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="DeleteLogFileTask" /> class.
- /// </summary>
- /// <param name="configurationManager">Instance of the <see cref="IConfigurationManager"/> interface.</param>
- /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
- /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
- public DeleteLogFileTask(IConfigurationManager configurationManager, IFileSystem fileSystem, ILocalizationManager localization)
- {
- _configurationManager = configurationManager;
- _fileSystem = fileSystem;
- _localization = localization;
- }
+ _configurationManager = configurationManager;
+ _fileSystem = fileSystem;
+ _localization = localization;
+ }
- /// <inheritdoc />
- public string Name => _localization.GetLocalizedString("TaskCleanLogs");
+ /// <inheritdoc />
+ public string Name => _localization.GetLocalizedString("TaskCleanLogs");
- /// <inheritdoc />
- public string Description => string.Format(
- CultureInfo.InvariantCulture,
- _localization.GetLocalizedString("TaskCleanLogsDescription"),
- _configurationManager.CommonConfiguration.LogFileRetentionDays);
+ /// <inheritdoc />
+ public string Description => string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("TaskCleanLogsDescription"),
+ _configurationManager.CommonConfiguration.LogFileRetentionDays);
- /// <inheritdoc />
- public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
+ /// <inheritdoc />
+ public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
- /// <inheritdoc />
- public string Key => "CleanLogFiles";
+ /// <inheritdoc />
+ public string Key => "CleanLogFiles";
- /// <inheritdoc />
- public bool IsHidden => false;
+ /// <inheritdoc />
+ public bool IsHidden => false;
- /// <inheritdoc />
- public bool IsEnabled => true;
+ /// <inheritdoc />
+ public bool IsEnabled => true;
- /// <inheritdoc />
- public bool IsLogged => true;
+ /// <inheritdoc />
+ public bool IsLogged => true;
- /// <inheritdoc />
- public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ /// <inheritdoc />
+ public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ {
+ yield return new TaskTriggerInfo
{
- return
- [
- new TaskTriggerInfo { Type = TaskTriggerInfoType.IntervalTrigger, IntervalTicks = TimeSpan.FromHours(24).Ticks }
- ];
- }
+ Type = TaskTriggerInfoType.IntervalTrigger,
+ IntervalTicks = TimeSpan.FromHours(24).Ticks
+ };
+ }
- /// <inheritdoc />
- public Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
- {
- // Delete log files more than n days old
- var minDateModified = DateTime.UtcNow.AddDays(-_configurationManager.CommonConfiguration.LogFileRetentionDays);
+ /// <inheritdoc />
+ public Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ // Delete log files more than n days old
+ var minDateModified = DateTime.UtcNow.AddDays(-_configurationManager.CommonConfiguration.LogFileRetentionDays);
- // Only delete files that serilog doesn't manage (anything that doesn't start with 'log_'
- var filesToDelete = _fileSystem.GetFiles(_configurationManager.CommonApplicationPaths.LogDirectoryPath, true)
- .Where(f => !f.Name.StartsWith("log_", StringComparison.Ordinal)
- && _fileSystem.GetLastWriteTimeUtc(f) < minDateModified)
- .ToList();
+ // Only delete files that serilog doesn't manage (anything that doesn't start with 'log_'
+ var filesToDelete = _fileSystem.GetFiles(_configurationManager.CommonApplicationPaths.LogDirectoryPath, true)
+ .Where(f => !f.Name.StartsWith("log_", StringComparison.Ordinal)
+ && _fileSystem.GetLastWriteTimeUtc(f) < minDateModified)
+ .ToList();
- var index = 0;
+ var index = 0;
- foreach (var file in filesToDelete)
- {
- double percent = index / (double)filesToDelete.Count;
+ foreach (var file in filesToDelete)
+ {
+ double percent = index / (double)filesToDelete.Count;
- progress.Report(100 * percent);
+ progress.Report(100 * percent);
- cancellationToken.ThrowIfCancellationRequested();
+ cancellationToken.ThrowIfCancellationRequested();
- _fileSystem.DeleteFile(file.FullName);
+ _fileSystem.DeleteFile(file.FullName);
- index++;
- }
+ index++;
+ }
- progress.Report(100);
+ progress.Report(100);
- return Task.CompletedTask;
- }
+ return Task.CompletedTask;
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs
index d0896cc81..9cc2cc512 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs
@@ -10,118 +10,115 @@ using MediaBrowser.Model.IO;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.ScheduledTasks.Tasks
+namespace Emby.Server.Implementations.ScheduledTasks.Tasks;
+
+/// <summary>
+/// Deletes all transcoding temp files.
+/// </summary>
+public class DeleteTranscodeFileTask : IScheduledTask, IConfigurableScheduledTask
{
+ private readonly ILogger<DeleteTranscodeFileTask> _logger;
+ private readonly IConfigurationManager _configurationManager;
+ private readonly IFileSystem _fileSystem;
+ private readonly ILocalizationManager _localization;
+
/// <summary>
- /// Deletes all transcoding temp files.
+ /// Initializes a new instance of the <see cref="DeleteTranscodeFileTask"/> class.
/// </summary>
- public class DeleteTranscodeFileTask : IScheduledTask, IConfigurableScheduledTask
+ /// <param name="logger">Instance of the <see cref="ILogger{DeleteTranscodeFileTask}"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="configurationManager">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
+ public DeleteTranscodeFileTask(
+ ILogger<DeleteTranscodeFileTask> logger,
+ IFileSystem fileSystem,
+ IConfigurationManager configurationManager,
+ ILocalizationManager localization)
{
- private readonly ILogger<DeleteTranscodeFileTask> _logger;
- private readonly IConfigurationManager _configurationManager;
- private readonly IFileSystem _fileSystem;
- private readonly ILocalizationManager _localization;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="DeleteTranscodeFileTask"/> class.
- /// </summary>
- /// <param name="logger">Instance of the <see cref="ILogger{DeleteTranscodeFileTask}"/> interface.</param>
- /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
- /// <param name="configurationManager">Instance of the <see cref="IConfigurationManager"/> interface.</param>
- /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
- public DeleteTranscodeFileTask(
- ILogger<DeleteTranscodeFileTask> logger,
- IFileSystem fileSystem,
- IConfigurationManager configurationManager,
- ILocalizationManager localization)
- {
- _logger = logger;
- _fileSystem = fileSystem;
- _configurationManager = configurationManager;
- _localization = localization;
- }
+ _logger = logger;
+ _fileSystem = fileSystem;
+ _configurationManager = configurationManager;
+ _localization = localization;
+ }
- /// <inheritdoc />
- public string Name => _localization.GetLocalizedString("TaskCleanTranscode");
+ /// <inheritdoc />
+ public string Name => _localization.GetLocalizedString("TaskCleanTranscode");
- /// <inheritdoc />
- public string Description => _localization.GetLocalizedString("TaskCleanTranscodeDescription");
+ /// <inheritdoc />
+ public string Description => _localization.GetLocalizedString("TaskCleanTranscodeDescription");
- /// <inheritdoc />
- public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
+ /// <inheritdoc />
+ public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
- /// <inheritdoc />
- public string Key => "DeleteTranscodeFiles";
+ /// <inheritdoc />
+ public string Key => "DeleteTranscodeFiles";
- /// <inheritdoc />
- public bool IsHidden => false;
+ /// <inheritdoc />
+ public bool IsHidden => false;
- /// <inheritdoc />
- public bool IsEnabled => true;
+ /// <inheritdoc />
+ public bool IsEnabled => true;
- /// <inheritdoc />
- public bool IsLogged => true;
+ /// <inheritdoc />
+ public bool IsLogged => true;
- /// <inheritdoc />
- public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ /// <inheritdoc />
+ public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ {
+ yield return new TaskTriggerInfo
{
- return
- [
- new TaskTriggerInfo
- {
- Type = TaskTriggerInfoType.StartupTrigger
- },
- new TaskTriggerInfo
- {
- Type = TaskTriggerInfoType.IntervalTrigger,
- IntervalTicks = TimeSpan.FromHours(24).Ticks
- }
- ];
- }
+ Type = TaskTriggerInfoType.StartupTrigger
+ };
- /// <inheritdoc />
- public Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
+ yield return new TaskTriggerInfo
{
- var minDateModified = DateTime.UtcNow.AddDays(-1);
- progress.Report(50);
-
- DeleteTempFilesFromDirectory(_configurationManager.GetTranscodePath(), minDateModified, progress, cancellationToken);
+ Type = TaskTriggerInfoType.IntervalTrigger,
+ IntervalTicks = TimeSpan.FromHours(24).Ticks
+ };
+ }
- return Task.CompletedTask;
- }
+ /// <inheritdoc />
+ public Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ var minDateModified = DateTime.UtcNow.AddDays(-1);
+ progress.Report(50);
- /// <summary>
- /// Deletes the transcoded temp files from directory with a last write time less than a given date.
- /// </summary>
- /// <param name="directory">The directory.</param>
- /// <param name="minDateModified">The min date modified.</param>
- /// <param name="progress">The progress.</param>
- /// <param name="cancellationToken">The task cancellation token.</param>
- private void DeleteTempFilesFromDirectory(string directory, DateTime minDateModified, IProgress<double> progress, CancellationToken cancellationToken)
- {
- var filesToDelete = _fileSystem.GetFiles(directory, true)
- .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified)
- .ToList();
+ DeleteTempFilesFromDirectory(_configurationManager.GetTranscodePath(), minDateModified, progress, cancellationToken);
- var index = 0;
+ return Task.CompletedTask;
+ }
- foreach (var file in filesToDelete)
- {
- double percent = index;
- percent /= filesToDelete.Count;
+ /// <summary>
+ /// Deletes the transcoded temp files from directory with a last write time less than a given date.
+ /// </summary>
+ /// <param name="directory">The directory.</param>
+ /// <param name="minDateModified">The min date modified.</param>
+ /// <param name="progress">The progress.</param>
+ /// <param name="cancellationToken">The task cancellation token.</param>
+ private void DeleteTempFilesFromDirectory(string directory, DateTime minDateModified, IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ var filesToDelete = _fileSystem.GetFiles(directory, true)
+ .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified)
+ .ToList();
- progress.Report(100 * percent);
+ var index = 0;
- cancellationToken.ThrowIfCancellationRequested();
+ foreach (var file in filesToDelete)
+ {
+ double percent = index;
+ percent /= filesToDelete.Count;
- FileSystemHelper.DeleteFile(_fileSystem, file.FullName, _logger);
+ progress.Report(100 * percent);
- index++;
- }
+ cancellationToken.ThrowIfCancellationRequested();
- FileSystemHelper.DeleteEmptyFolders(_fileSystem, directory, _logger);
+ FileSystemHelper.DeleteFile(_fileSystem, file.FullName, _logger);
- progress.Report(100);
+ index++;
}
+
+ FileSystemHelper.DeleteEmptyFolders(_fileSystem, directory, _logger);
+
+ progress.Report(100);
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/MediaSegmentExtractionTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/MediaSegmentExtractionTask.cs
index de1e60d30..51920c5b1 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/MediaSegmentExtractionTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/MediaSegmentExtractionTask.cs
@@ -4,10 +4,10 @@ using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Data.Enums;
-using MediaBrowser.Controller;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaSegments;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Tasks;
@@ -62,11 +62,11 @@ public class MediaSegmentExtractionTask : IScheduledTask
var query = new InternalItemsQuery
{
- MediaTypes = new[] { MediaType.Video, MediaType.Audio },
+ MediaTypes = [MediaType.Video, MediaType.Audio],
IsVirtualItem = false,
IncludeItemTypes = _itemTypes,
DtoOptions = new DtoOptions(true),
- SourceTypes = new[] { SourceType.Library },
+ SourceTypes = [SourceType.Library],
Recursive = true,
Limit = pagesize
};
@@ -91,7 +91,8 @@ public class MediaSegmentExtractionTask : IScheduledTask
// Only local files supported
if (item.IsFileProtocol && File.Exists(item.Path))
{
- await _mediaSegmentManager.RunSegmentPluginProviders(item, false, cancellationToken).ConfigureAwait(false);
+ var libraryOptions = _libraryManager.GetLibraryOptions(item);
+ await _mediaSegmentManager.RunSegmentPluginProviders(item, libraryOptions, false, cancellationToken).ConfigureAwait(false);
}
// Update progress
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/OptimizeDatabaseTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/OptimizeDatabaseTask.cs
index 4d3a04377..bf8ffaf47 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/OptimizeDatabaseTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/OptimizeDatabaseTask.cs
@@ -5,84 +5,78 @@ using System.Threading.Tasks;
using Jellyfin.Database.Implementations;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Tasks;
-using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.ScheduledTasks.Tasks
+namespace Emby.Server.Implementations.ScheduledTasks.Tasks;
+
+/// <summary>
+/// Optimizes Jellyfin's database by issuing a VACUUM command.
+/// </summary>
+public class OptimizeDatabaseTask : IScheduledTask, IConfigurableScheduledTask
{
+ private readonly ILogger<OptimizeDatabaseTask> _logger;
+ private readonly ILocalizationManager _localization;
+ private readonly IJellyfinDatabaseProvider _jellyfinDatabaseProvider;
+
/// <summary>
- /// Optimizes Jellyfin's database by issuing a VACUUM command.
+ /// Initializes a new instance of the <see cref="OptimizeDatabaseTask" /> class.
/// </summary>
- public class OptimizeDatabaseTask : IScheduledTask, IConfigurableScheduledTask
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
+ /// <param name="jellyfinDatabaseProvider">Instance of the JellyfinDatabaseProvider that can be used for provider specific operations.</param>
+ public OptimizeDatabaseTask(
+ ILogger<OptimizeDatabaseTask> logger,
+ ILocalizationManager localization,
+ IJellyfinDatabaseProvider jellyfinDatabaseProvider)
{
- private readonly ILogger<OptimizeDatabaseTask> _logger;
- private readonly ILocalizationManager _localization;
- private readonly IDbContextFactory<JellyfinDbContext> _provider;
- private readonly IJellyfinDatabaseProvider _jellyfinDatabaseProvider;
+ _logger = logger;
+ _localization = localization;
+ _jellyfinDatabaseProvider = jellyfinDatabaseProvider;
+ }
- /// <summary>
- /// Initializes a new instance of the <see cref="OptimizeDatabaseTask" /> class.
- /// </summary>
- /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
- /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
- /// <param name="provider">Instance of the <see cref="IDbContextFactory{JellyfinDbContext}"/> interface.</param>
- /// <param name="jellyfinDatabaseProvider">Instance of the JellyfinDatabaseProvider that can be used for provider specific operations.</param>
- public OptimizeDatabaseTask(
- ILogger<OptimizeDatabaseTask> logger,
- ILocalizationManager localization,
- IDbContextFactory<JellyfinDbContext> provider,
- IJellyfinDatabaseProvider jellyfinDatabaseProvider)
- {
- _logger = logger;
- _localization = localization;
- _provider = provider;
- _jellyfinDatabaseProvider = jellyfinDatabaseProvider;
- }
+ /// <inheritdoc />
+ public string Name => _localization.GetLocalizedString("TaskOptimizeDatabase");
+
+ /// <inheritdoc />
+ public string Description => _localization.GetLocalizedString("TaskOptimizeDatabaseDescription");
- /// <inheritdoc />
- public string Name => _localization.GetLocalizedString("TaskOptimizeDatabase");
+ /// <inheritdoc />
+ public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
- /// <inheritdoc />
- public string Description => _localization.GetLocalizedString("TaskOptimizeDatabaseDescription");
+ /// <inheritdoc />
+ public string Key => "OptimizeDatabaseTask";
- /// <inheritdoc />
- public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
+ /// <inheritdoc />
+ public bool IsHidden => false;
- /// <inheritdoc />
- public string Key => "OptimizeDatabaseTask";
+ /// <inheritdoc />
+ public bool IsEnabled => true;
- /// <inheritdoc />
- public bool IsHidden => false;
+ /// <inheritdoc />
+ public bool IsLogged => true;
- /// <inheritdoc />
- public bool IsEnabled => true;
+ /// <inheritdoc />
+ public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ {
+ yield return new TaskTriggerInfo
+ {
+ Type = TaskTriggerInfoType.IntervalTrigger,
+ IntervalTicks = TimeSpan.FromHours(24).Ticks
+ };
+ }
- /// <inheritdoc />
- public bool IsLogged => true;
+ /// <inheritdoc />
+ public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ _logger.LogInformation("Optimizing and vacuuming jellyfin.db...");
- /// <inheritdoc />
- public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ try
{
- return
- [
- // Every so often
- new TaskTriggerInfo { Type = TaskTriggerInfoType.IntervalTrigger, IntervalTicks = TimeSpan.FromHours(24).Ticks }
- ];
+ await _jellyfinDatabaseProvider.RunScheduledOptimisation(cancellationToken).ConfigureAwait(false);
}
-
- /// <inheritdoc />
- public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
+ catch (Exception e)
{
- _logger.LogInformation("Optimizing and vacuuming jellyfin.db...");
-
- try
- {
- await _jellyfinDatabaseProvider.RunScheduledOptimisation(cancellationToken).ConfigureAwait(false);
- }
- catch (Exception e)
- {
- _logger.LogError(e, "Error while optimizing jellyfin.db");
- }
+ _logger.LogError(e, "Error while optimizing jellyfin.db");
}
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/PeopleValidationTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/PeopleValidationTask.cs
index 2907f18b5..18162ad2f 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/PeopleValidationTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/PeopleValidationTask.cs
@@ -6,68 +6,64 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Tasks;
-namespace Emby.Server.Implementations.ScheduledTasks.Tasks
+namespace Emby.Server.Implementations.ScheduledTasks.Tasks;
+
+/// <summary>
+/// Class PeopleValidationTask.
+/// </summary>
+public class PeopleValidationTask : IScheduledTask, IConfigurableScheduledTask
{
+ private readonly ILibraryManager _libraryManager;
+ private readonly ILocalizationManager _localization;
+
/// <summary>
- /// Class PeopleValidationTask.
+ /// Initializes a new instance of the <see cref="PeopleValidationTask" /> class.
/// </summary>
- public class PeopleValidationTask : IScheduledTask, IConfigurableScheduledTask
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
+ public PeopleValidationTask(ILibraryManager libraryManager, ILocalizationManager localization)
{
- private readonly ILibraryManager _libraryManager;
- private readonly ILocalizationManager _localization;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="PeopleValidationTask" /> class.
- /// </summary>
- /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
- /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
- public PeopleValidationTask(ILibraryManager libraryManager, ILocalizationManager localization)
- {
- _libraryManager = libraryManager;
- _localization = localization;
- }
+ _libraryManager = libraryManager;
+ _localization = localization;
+ }
- /// <inheritdoc />
- public string Name => _localization.GetLocalizedString("TaskRefreshPeople");
+ /// <inheritdoc />
+ public string Name => _localization.GetLocalizedString("TaskRefreshPeople");
- /// <inheritdoc />
- public string Description => _localization.GetLocalizedString("TaskRefreshPeopleDescription");
+ /// <inheritdoc />
+ public string Description => _localization.GetLocalizedString("TaskRefreshPeopleDescription");
- /// <inheritdoc />
- public string Category => _localization.GetLocalizedString("TasksLibraryCategory");
+ /// <inheritdoc />
+ public string Category => _localization.GetLocalizedString("TasksLibraryCategory");
- /// <inheritdoc />
- public string Key => "RefreshPeople";
+ /// <inheritdoc />
+ public string Key => "RefreshPeople";
- /// <inheritdoc />
- public bool IsHidden => false;
+ /// <inheritdoc />
+ public bool IsHidden => false;
- /// <inheritdoc />
- public bool IsEnabled => true;
+ /// <inheritdoc />
+ public bool IsEnabled => true;
- /// <inheritdoc />
- public bool IsLogged => true;
+ /// <inheritdoc />
+ public bool IsLogged => true;
- /// <summary>
- /// Creates the triggers that define when the task will run.
- /// </summary>
- /// <returns>An <see cref="IEnumerable{TaskTriggerInfo}"/> containing the default trigger infos for this task.</returns>
- public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ /// <summary>
+ /// Creates the triggers that define when the task will run.
+ /// </summary>
+ /// <returns>An <see cref="IEnumerable{TaskTriggerInfo}"/> containing the default trigger infos for this task.</returns>
+ public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ {
+ yield return new TaskTriggerInfo
{
- return new[]
- {
- new TaskTriggerInfo
- {
- Type = TaskTriggerInfoType.IntervalTrigger,
- IntervalTicks = TimeSpan.FromDays(7).Ticks
- }
- };
- }
+ Type = TaskTriggerInfoType.IntervalTrigger,
+ IntervalTicks = TimeSpan.FromDays(7).Ticks
+ };
+ }
- /// <inheritdoc />
- public Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
- {
- return _libraryManager.ValidatePeopleAsync(progress, cancellationToken);
- }
+ /// <inheritdoc />
+ public Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ return _libraryManager.ValidatePeopleAsync(progress, cancellationToken);
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs
index b74f4d1b2..31153af20 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs
@@ -10,111 +10,115 @@ using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.ScheduledTasks.Tasks
+namespace Emby.Server.Implementations.ScheduledTasks.Tasks;
+
+/// <summary>
+/// Plugin Update Task.
+/// </summary>
+public class PluginUpdateTask : IScheduledTask, IConfigurableScheduledTask
{
+ private readonly ILogger<PluginUpdateTask> _logger;
+
+ private readonly IInstallationManager _installationManager;
+ private readonly ILocalizationManager _localization;
+
/// <summary>
- /// Plugin Update Task.
+ /// Initializes a new instance of the <see cref="PluginUpdateTask" /> class.
/// </summary>
- public class PluginUpdateTask : IScheduledTask, IConfigurableScheduledTask
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="installationManager">Instance of the <see cref="IInstallationManager"/> interface.</param>
+ /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
+ public PluginUpdateTask(ILogger<PluginUpdateTask> logger, IInstallationManager installationManager, ILocalizationManager localization)
{
- private readonly ILogger<PluginUpdateTask> _logger;
-
- private readonly IInstallationManager _installationManager;
- private readonly ILocalizationManager _localization;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="PluginUpdateTask" /> class.
- /// </summary>
- /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
- /// <param name="installationManager">Instance of the <see cref="IInstallationManager"/> interface.</param>
- /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
- public PluginUpdateTask(ILogger<PluginUpdateTask> logger, IInstallationManager installationManager, ILocalizationManager localization)
- {
- _logger = logger;
- _installationManager = installationManager;
- _localization = localization;
- }
+ _logger = logger;
+ _installationManager = installationManager;
+ _localization = localization;
+ }
- /// <inheritdoc />
- public string Name => _localization.GetLocalizedString("TaskUpdatePlugins");
+ /// <inheritdoc />
+ public string Name => _localization.GetLocalizedString("TaskUpdatePlugins");
- /// <inheritdoc />
- public string Description => _localization.GetLocalizedString("TaskUpdatePluginsDescription");
+ /// <inheritdoc />
+ public string Description => _localization.GetLocalizedString("TaskUpdatePluginsDescription");
- /// <inheritdoc />
- public string Category => _localization.GetLocalizedString("TasksApplicationCategory");
+ /// <inheritdoc />
+ public string Category => _localization.GetLocalizedString("TasksApplicationCategory");
- /// <inheritdoc />
- public string Key => "PluginUpdates";
+ /// <inheritdoc />
+ public string Key => "PluginUpdates";
- /// <inheritdoc />
- public bool IsHidden => false;
+ /// <inheritdoc />
+ public bool IsHidden => false;
- /// <inheritdoc />
- public bool IsEnabled => true;
+ /// <inheritdoc />
+ public bool IsEnabled => true;
- /// <inheritdoc />
- public bool IsLogged => true;
+ /// <inheritdoc />
+ public bool IsLogged => true;
- /// <inheritdoc />
- public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ /// <inheritdoc />
+ public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ {
+ yield return new TaskTriggerInfo
{
- // At startup
- yield return new TaskTriggerInfo { Type = TaskTriggerInfoType.StartupTrigger };
-
- // Every so often
- yield return new TaskTriggerInfo { Type = TaskTriggerInfoType.IntervalTrigger, IntervalTicks = TimeSpan.FromHours(24).Ticks };
- }
+ Type = TaskTriggerInfoType.StartupTrigger
+ };
- /// <inheritdoc />
- public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
+ yield return new TaskTriggerInfo
{
- progress.Report(0);
+ Type = TaskTriggerInfoType.IntervalTrigger,
+ IntervalTicks = TimeSpan.FromHours(24).Ticks
+ };
+ }
- var packageFetchTask = _installationManager.GetAvailablePluginUpdates(cancellationToken);
- var packagesToInstall = (await packageFetchTask.ConfigureAwait(false)).ToList();
+ /// <inheritdoc />
+ public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ progress.Report(0);
- progress.Report(10);
+ var packageFetchTask = _installationManager.GetAvailablePluginUpdates(cancellationToken);
+ var packagesToInstall = (await packageFetchTask.ConfigureAwait(false)).ToList();
- var numComplete = 0;
+ progress.Report(10);
- foreach (var package in packagesToInstall)
- {
- cancellationToken.ThrowIfCancellationRequested();
+ var numComplete = 0;
- try
- {
- await _installationManager.InstallPackage(package, cancellationToken).ConfigureAwait(false);
- }
- catch (OperationCanceledException)
- {
- // InstallPackage has its own inner cancellation token, so only throw this if it's ours
- if (cancellationToken.IsCancellationRequested)
- {
- throw;
- }
- }
- catch (HttpRequestException ex)
- {
- _logger.LogError(ex, "Error downloading {0}", package.Name);
- }
- catch (IOException ex)
- {
- _logger.LogError(ex, "Error updating {0}", package.Name);
- }
- catch (InvalidDataException ex)
- {
- _logger.LogError(ex, "Error updating {0}", package.Name);
- }
+ foreach (var package in packagesToInstall)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
- // Update progress
- lock (progress)
+ try
+ {
+ await _installationManager.InstallPackage(package, cancellationToken).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ // InstallPackage has its own inner cancellation token, so only throw this if it's ours
+ if (cancellationToken.IsCancellationRequested)
{
- progress.Report((90.0 * ++numComplete / packagesToInstall.Count) + 10);
+ throw;
}
}
+ catch (HttpRequestException ex)
+ {
+ _logger.LogError(ex, "Error downloading {Name}", package.Name);
+ }
+ catch (IOException ex)
+ {
+ _logger.LogError(ex, "Error updating {Name}", package.Name);
+ }
+ catch (InvalidDataException ex)
+ {
+ _logger.LogError(ex, "Error updating {Name}", package.Name);
+ }
- progress.Report(100);
+ // Update progress
+ lock (progress)
+ {
+ progress.Report((90.0 * ++numComplete / packagesToInstall.Count) + 10);
+ }
}
+
+ progress.Report(100);
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/RefreshMediaLibraryTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/RefreshMediaLibraryTask.cs
index 172448dde..c96843199 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Tasks/RefreshMediaLibraryTask.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/RefreshMediaLibraryTask.cs
@@ -7,60 +7,59 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Tasks;
-namespace Emby.Server.Implementations.ScheduledTasks.Tasks
+namespace Emby.Server.Implementations.ScheduledTasks.Tasks;
+
+/// <summary>
+/// Class RefreshMediaLibraryTask.
+/// </summary>
+public class RefreshMediaLibraryTask : IScheduledTask
{
/// <summary>
- /// Class RefreshMediaLibraryTask.
+ /// The _library manager.
/// </summary>
- public class RefreshMediaLibraryTask : IScheduledTask
- {
- /// <summary>
- /// The _library manager.
- /// </summary>
- private readonly ILibraryManager _libraryManager;
- private readonly ILocalizationManager _localization;
+ private readonly ILibraryManager _libraryManager;
+ private readonly ILocalizationManager _localization;
- /// <summary>
- /// Initializes a new instance of the <see cref="RefreshMediaLibraryTask" /> class.
- /// </summary>
- /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
- /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
- public RefreshMediaLibraryTask(ILibraryManager libraryManager, ILocalizationManager localization)
- {
- _libraryManager = libraryManager;
- _localization = localization;
- }
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RefreshMediaLibraryTask" /> class.
+ /// </summary>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
+ public RefreshMediaLibraryTask(ILibraryManager libraryManager, ILocalizationManager localization)
+ {
+ _libraryManager = libraryManager;
+ _localization = localization;
+ }
- /// <inheritdoc />
- public string Name => _localization.GetLocalizedString("TaskRefreshLibrary");
+ /// <inheritdoc />
+ public string Name => _localization.GetLocalizedString("TaskRefreshLibrary");
- /// <inheritdoc />
- public string Description => _localization.GetLocalizedString("TaskRefreshLibraryDescription");
+ /// <inheritdoc />
+ public string Description => _localization.GetLocalizedString("TaskRefreshLibraryDescription");
- /// <inheritdoc />
- public string Category => _localization.GetLocalizedString("TasksLibraryCategory");
+ /// <inheritdoc />
+ public string Category => _localization.GetLocalizedString("TasksLibraryCategory");
- /// <inheritdoc />
- public string Key => "RefreshLibrary";
+ /// <inheritdoc />
+ public string Key => "RefreshLibrary";
- /// <inheritdoc />
- public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ /// <inheritdoc />
+ public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ {
+ yield return new TaskTriggerInfo
{
- yield return new TaskTriggerInfo
- {
- Type = TaskTriggerInfoType.IntervalTrigger,
- IntervalTicks = TimeSpan.FromHours(12).Ticks
- };
- }
+ Type = TaskTriggerInfoType.IntervalTrigger,
+ IntervalTicks = TimeSpan.FromHours(12).Ticks
+ };
+ }
- /// <inheritdoc />
- public Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
- {
- cancellationToken.ThrowIfCancellationRequested();
+ /// <inheritdoc />
+ public Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
- progress.Report(0);
+ progress.Report(0);
- return ((LibraryManager)_libraryManager).ValidateMediaLibraryInternal(progress, cancellationToken);
- }
+ return ((LibraryManager)_libraryManager).ValidateMediaLibraryInternal(progress, cancellationToken);
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs
index 6d2a74da4..9abcd9c7b 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs
@@ -3,85 +3,84 @@ using System.Threading;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.ScheduledTasks.Triggers
+namespace Emby.Server.Implementations.ScheduledTasks.Triggers;
+
+/// <summary>
+/// Represents a task trigger that fires everyday.
+/// </summary>
+public sealed class DailyTrigger : ITaskTrigger, IDisposable
{
+ private readonly TimeSpan _timeOfDay;
+ private Timer? _timer;
+ private bool _disposed;
+
/// <summary>
- /// Represents a task trigger that fires everyday.
+ /// Initializes a new instance of the <see cref="DailyTrigger"/> class.
/// </summary>
- public sealed class DailyTrigger : ITaskTrigger, IDisposable
+ /// <param name="timeOfDay">The time of day to trigger the task to run.</param>
+ /// <param name="taskOptions">The options of this task.</param>
+ public DailyTrigger(TimeSpan timeOfDay, TaskOptions taskOptions)
{
- private readonly TimeSpan _timeOfDay;
- private Timer? _timer;
- private bool _disposed = false;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="DailyTrigger"/> class.
- /// </summary>
- /// <param name="timeofDay">The time of day to trigger the task to run.</param>
- /// <param name="taskOptions">The options of this task.</param>
- public DailyTrigger(TimeSpan timeofDay, TaskOptions taskOptions)
- {
- _timeOfDay = timeofDay;
- TaskOptions = taskOptions;
- }
+ _timeOfDay = timeOfDay;
+ TaskOptions = taskOptions;
+ }
- /// <inheritdoc />
- public event EventHandler<EventArgs>? Triggered;
+ /// <inheritdoc />
+ public event EventHandler<EventArgs>? Triggered;
- /// <inheritdoc />
- public TaskOptions TaskOptions { get; }
+ /// <inheritdoc />
+ public TaskOptions TaskOptions { get; }
- /// <inheritdoc />
- public void Start(TaskResult? lastResult, ILogger logger, string taskName, bool isApplicationStartup)
- {
- DisposeTimer();
+ /// <inheritdoc />
+ public void Start(TaskResult? lastResult, ILogger logger, string taskName, bool isApplicationStartup)
+ {
+ DisposeTimer();
- var now = DateTime.Now;
+ var now = DateTime.Now;
- var triggerDate = now.TimeOfDay > _timeOfDay ? now.Date.AddDays(1) : now.Date;
- triggerDate = triggerDate.Add(_timeOfDay);
+ var triggerDate = now.TimeOfDay > _timeOfDay ? now.Date.AddDays(1) : now.Date;
+ triggerDate = triggerDate.Add(_timeOfDay);
- var dueTime = triggerDate - now;
+ var dueTime = triggerDate - now;
- logger.LogInformation("Daily trigger for {Task} set to fire at {TriggerDate:yyyy-MM-dd HH:mm:ss.fff zzz}, which is {DueTime:c} from now.", taskName, triggerDate, dueTime);
+ logger.LogInformation("Daily trigger for {Task} set to fire at {TriggerDate:yyyy-MM-dd HH:mm:ss.fff zzz}, which is {DueTime:c} from now.", taskName, triggerDate, dueTime);
- _timer = new Timer(_ => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1));
- }
+ _timer = new Timer(_ => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1));
+ }
- /// <inheritdoc />
- public void Stop()
- {
- DisposeTimer();
- }
+ /// <inheritdoc />
+ public void Stop()
+ {
+ DisposeTimer();
+ }
- /// <summary>
- /// Disposes the timer.
- /// </summary>
- private void DisposeTimer()
- {
- _timer?.Dispose();
- _timer = null;
- }
+ /// <summary>
+ /// Disposes the timer.
+ /// </summary>
+ private void DisposeTimer()
+ {
+ _timer?.Dispose();
+ _timer = null;
+ }
- /// <summary>
- /// Called when [triggered].
- /// </summary>
- private void OnTriggered()
- {
- Triggered?.Invoke(this, EventArgs.Empty);
- }
+ /// <summary>
+ /// Called when [triggered].
+ /// </summary>
+ private void OnTriggered()
+ {
+ Triggered?.Invoke(this, EventArgs.Empty);
+ }
- /// <inheritdoc />
- public void Dispose()
+ /// <inheritdoc />
+ public void Dispose()
+ {
+ if (_disposed)
{
- if (_disposed)
- {
- return;
- }
+ return;
+ }
- DisposeTimer();
+ DisposeTimer();
- _disposed = true;
- }
+ _disposed = true;
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Triggers/IntervalTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/Triggers/IntervalTrigger.cs
index 9425b47d0..d6773b65e 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Triggers/IntervalTrigger.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Triggers/IntervalTrigger.cs
@@ -4,104 +4,103 @@ using System.Threading;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.ScheduledTasks.Triggers
+namespace Emby.Server.Implementations.ScheduledTasks.Triggers;
+
+/// <summary>
+/// Represents a task trigger that runs repeatedly on an interval.
+/// </summary>
+public sealed class IntervalTrigger : ITaskTrigger, IDisposable
{
+ private readonly TimeSpan _interval;
+ private DateTime _lastStartDate;
+ private Timer? _timer;
+ private bool _disposed;
+
/// <summary>
- /// Represents a task trigger that runs repeatedly on an interval.
+ /// Initializes a new instance of the <see cref="IntervalTrigger"/> class.
/// </summary>
- public sealed class IntervalTrigger : ITaskTrigger, IDisposable
+ /// <param name="interval">The interval.</param>
+ /// <param name="taskOptions">The options of this task.</param>
+ public IntervalTrigger(TimeSpan interval, TaskOptions taskOptions)
{
- private readonly TimeSpan _interval;
- private DateTime _lastStartDate;
- private Timer? _timer;
- private bool _disposed = false;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="IntervalTrigger"/> class.
- /// </summary>
- /// <param name="interval">The interval.</param>
- /// <param name="taskOptions">The options of this task.</param>
- public IntervalTrigger(TimeSpan interval, TaskOptions taskOptions)
- {
- _interval = interval;
- TaskOptions = taskOptions;
- }
+ _interval = interval;
+ TaskOptions = taskOptions;
+ }
+
+ /// <inheritdoc />
+ public event EventHandler<EventArgs>? Triggered;
- /// <inheritdoc />
- public event EventHandler<EventArgs>? Triggered;
+ /// <inheritdoc />
+ public TaskOptions TaskOptions { get; }
+
+ /// <inheritdoc />
+ public void Start(TaskResult? lastResult, ILogger logger, string taskName, bool isApplicationStartup)
+ {
+ DisposeTimer();
- /// <inheritdoc />
- public TaskOptions TaskOptions { get; }
+ DateTime now = DateTime.UtcNow;
+ DateTime triggerDate;
- /// <inheritdoc />
- public void Start(TaskResult? lastResult, ILogger logger, string taskName, bool isApplicationStartup)
+ if (lastResult is null)
{
- DisposeTimer();
-
- DateTime now = DateTime.UtcNow;
- DateTime triggerDate;
-
- if (lastResult is null)
- {
- // Task has never been completed before
- triggerDate = now.AddHours(1);
- }
- else
- {
- triggerDate = new[] { lastResult.EndTimeUtc, _lastStartDate, now.AddMinutes(1) }.Max().Add(_interval);
- }
-
- var dueTime = triggerDate - now;
- var maxDueTime = TimeSpan.FromDays(7);
-
- if (dueTime > maxDueTime)
- {
- dueTime = maxDueTime;
- }
-
- _timer = new Timer(_ => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1));
+ // Task has never been completed before
+ triggerDate = now.AddHours(1);
}
-
- /// <inheritdoc />
- public void Stop()
+ else
{
- DisposeTimer();
+ triggerDate = new[] { lastResult.EndTimeUtc, _lastStartDate, now.AddMinutes(1) }.Max().Add(_interval);
}
- /// <summary>
- /// Disposes the timer.
- /// </summary>
- private void DisposeTimer()
+ var dueTime = triggerDate - now;
+ var maxDueTime = TimeSpan.FromDays(7);
+
+ if (dueTime > maxDueTime)
{
- _timer?.Dispose();
- _timer = null;
+ dueTime = maxDueTime;
}
- /// <summary>
- /// Called when [triggered].
- /// </summary>
- private void OnTriggered()
- {
- DisposeTimer();
+ _timer = new Timer(_ => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1));
+ }
+
+ /// <inheritdoc />
+ public void Stop()
+ {
+ DisposeTimer();
+ }
- if (Triggered is not null)
- {
- _lastStartDate = DateTime.UtcNow;
- Triggered(this, EventArgs.Empty);
- }
+ /// <summary>
+ /// Disposes the timer.
+ /// </summary>
+ private void DisposeTimer()
+ {
+ _timer?.Dispose();
+ _timer = null;
+ }
+
+ /// <summary>
+ /// Called when [triggered].
+ /// </summary>
+ private void OnTriggered()
+ {
+ DisposeTimer();
+
+ if (Triggered is not null)
+ {
+ _lastStartDate = DateTime.UtcNow;
+ Triggered(this, EventArgs.Empty);
}
+ }
- /// <inheritdoc />
- public void Dispose()
+ /// <inheritdoc />
+ public void Dispose()
+ {
+ if (_disposed)
{
- if (_disposed)
- {
- return;
- }
+ return;
+ }
- DisposeTimer();
+ DisposeTimer();
- _disposed = true;
- }
+ _disposed = true;
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Triggers/StartupTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/Triggers/StartupTrigger.cs
index 535aa20f9..86ceff6ce 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Triggers/StartupTrigger.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Triggers/StartupTrigger.cs
@@ -3,52 +3,51 @@ using System.Threading.Tasks;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.ScheduledTasks.Triggers
+namespace Emby.Server.Implementations.ScheduledTasks.Triggers;
+
+/// <summary>
+/// Class StartupTaskTrigger.
+/// </summary>
+public sealed class StartupTrigger : ITaskTrigger
{
+ private const int DelayMs = 3000;
+
/// <summary>
- /// Class StartupTaskTrigger.
+ /// Initializes a new instance of the <see cref="StartupTrigger"/> class.
/// </summary>
- public sealed class StartupTrigger : ITaskTrigger
+ /// <param name="taskOptions">The options of this task.</param>
+ public StartupTrigger(TaskOptions taskOptions)
{
- private const int DelayMs = 3000;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="StartupTrigger"/> class.
- /// </summary>
- /// <param name="taskOptions">The options of this task.</param>
- public StartupTrigger(TaskOptions taskOptions)
- {
- TaskOptions = taskOptions;
- }
+ TaskOptions = taskOptions;
+ }
- /// <inheritdoc />
- public event EventHandler<EventArgs>? Triggered;
+ /// <inheritdoc />
+ public event EventHandler<EventArgs>? Triggered;
- /// <inheritdoc />
- public TaskOptions TaskOptions { get; }
+ /// <inheritdoc />
+ public TaskOptions TaskOptions { get; }
- /// <inheritdoc />
- public async void Start(TaskResult? lastResult, ILogger logger, string taskName, bool isApplicationStartup)
+ /// <inheritdoc />
+ public async void Start(TaskResult? lastResult, ILogger logger, string taskName, bool isApplicationStartup)
+ {
+ if (isApplicationStartup)
{
- if (isApplicationStartup)
- {
- await Task.Delay(DelayMs).ConfigureAwait(false);
+ await Task.Delay(DelayMs).ConfigureAwait(false);
- OnTriggered();
- }
+ OnTriggered();
}
+ }
- /// <inheritdoc />
- public void Stop()
- {
- }
+ /// <inheritdoc />
+ public void Stop()
+ {
+ }
- /// <summary>
- /// Called when [triggered].
- /// </summary>
- private void OnTriggered()
- {
- Triggered?.Invoke(this, EventArgs.Empty);
- }
+ /// <summary>
+ /// Called when [triggered].
+ /// </summary>
+ private void OnTriggered()
+ {
+ Triggered?.Invoke(this, EventArgs.Empty);
}
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/Triggers/WeeklyTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/Triggers/WeeklyTrigger.cs
index ad94fdda5..79568f8a1 100644
--- a/Emby.Server.Implementations/ScheduledTasks/Triggers/WeeklyTrigger.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/Triggers/WeeklyTrigger.cs
@@ -3,108 +3,107 @@ using System.Threading;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
-namespace Emby.Server.Implementations.ScheduledTasks.Triggers
+namespace Emby.Server.Implementations.ScheduledTasks.Triggers;
+
+/// <summary>
+/// Represents a task trigger that fires on a weekly basis.
+/// </summary>
+public sealed class WeeklyTrigger : ITaskTrigger, IDisposable
{
+ private readonly TimeSpan _timeOfDay;
+ private readonly DayOfWeek _dayOfWeek;
+ private Timer? _timer;
+ private bool _disposed;
+
/// <summary>
- /// Represents a task trigger that fires on a weekly basis.
+ /// Initializes a new instance of the <see cref="WeeklyTrigger"/> class.
/// </summary>
- public sealed class WeeklyTrigger : ITaskTrigger, IDisposable
+ /// <param name="timeOfDay">The time of day to trigger the task to run.</param>
+ /// <param name="dayOfWeek">The day of week.</param>
+ /// <param name="taskOptions">The options of this task.</param>
+ public WeeklyTrigger(TimeSpan timeOfDay, DayOfWeek dayOfWeek, TaskOptions taskOptions)
{
- private readonly TimeSpan _timeOfDay;
- private readonly DayOfWeek _dayOfWeek;
- private Timer? _timer;
- private bool _disposed;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="WeeklyTrigger"/> class.
- /// </summary>
- /// <param name="timeofDay">The time of day to trigger the task to run.</param>
- /// <param name="dayOfWeek">The day of week.</param>
- /// <param name="taskOptions">The options of this task.</param>
- public WeeklyTrigger(TimeSpan timeofDay, DayOfWeek dayOfWeek, TaskOptions taskOptions)
- {
- _timeOfDay = timeofDay;
- _dayOfWeek = dayOfWeek;
- TaskOptions = taskOptions;
- }
+ _timeOfDay = timeOfDay;
+ _dayOfWeek = dayOfWeek;
+ TaskOptions = taskOptions;
+ }
- /// <inheritdoc />
- public event EventHandler<EventArgs>? Triggered;
+ /// <inheritdoc />
+ public event EventHandler<EventArgs>? Triggered;
- /// <inheritdoc />
- public TaskOptions TaskOptions { get; }
+ /// <inheritdoc />
+ public TaskOptions TaskOptions { get; }
- /// <inheritdoc />
- public void Start(TaskResult? lastResult, ILogger logger, string taskName, bool isApplicationStartup)
- {
- DisposeTimer();
+ /// <inheritdoc />
+ public void Start(TaskResult? lastResult, ILogger logger, string taskName, bool isApplicationStartup)
+ {
+ DisposeTimer();
- var triggerDate = GetNextTriggerDateTime();
+ var triggerDate = GetNextTriggerDateTime();
- _timer = new Timer(_ => OnTriggered(), null, triggerDate - DateTime.Now, TimeSpan.FromMilliseconds(-1));
- }
+ _timer = new Timer(_ => OnTriggered(), null, triggerDate - DateTime.Now, TimeSpan.FromMilliseconds(-1));
+ }
- /// <summary>
- /// Gets the next trigger date time.
- /// </summary>
- /// <returns>DateTime.</returns>
- private DateTime GetNextTriggerDateTime()
+ /// <summary>
+ /// Gets the next trigger date time.
+ /// </summary>
+ /// <returns>DateTime.</returns>
+ private DateTime GetNextTriggerDateTime()
+ {
+ var now = DateTime.Now;
+
+ // If it's on the same day
+ if (now.DayOfWeek == _dayOfWeek)
{
- var now = DateTime.Now;
+ // It's either later today, or a week from now
+ return now.TimeOfDay < _timeOfDay ? now.Date.Add(_timeOfDay) : now.Date.AddDays(7).Add(_timeOfDay);
+ }
- // If it's on the same day
- if (now.DayOfWeek == _dayOfWeek)
- {
- // It's either later today, or a week from now
- return now.TimeOfDay < _timeOfDay ? now.Date.Add(_timeOfDay) : now.Date.AddDays(7).Add(_timeOfDay);
- }
+ var triggerDate = now.Date;
- var triggerDate = now.Date;
+ // Walk the date forward until we get to the trigger day
+ while (triggerDate.DayOfWeek != _dayOfWeek)
+ {
+ triggerDate = triggerDate.AddDays(1);
+ }
- // Walk the date forward until we get to the trigger day
- while (triggerDate.DayOfWeek != _dayOfWeek)
- {
- triggerDate = triggerDate.AddDays(1);
- }
+ // Return the trigger date plus the time offset
+ return triggerDate.Add(_timeOfDay);
+ }
- // Return the trigger date plus the time offset
- return triggerDate.Add(_timeOfDay);
- }
+ /// <inheritdoc />
+ public void Stop()
+ {
+ DisposeTimer();
+ }
- /// <inheritdoc />
- public void Stop()
- {
- DisposeTimer();
- }
+ /// <summary>
+ /// Disposes the timer.
+ /// </summary>
+ private void DisposeTimer()
+ {
+ _timer?.Dispose();
+ _timer = null;
+ }
- /// <summary>
- /// Disposes the timer.
- /// </summary>
- private void DisposeTimer()
- {
- _timer?.Dispose();
- _timer = null;
- }
+ /// <summary>
+ /// Called when [triggered].
+ /// </summary>
+ private void OnTriggered()
+ {
+ Triggered?.Invoke(this, EventArgs.Empty);
+ }
- /// <summary>
- /// Called when [triggered].
- /// </summary>
- private void OnTriggered()
+ /// <inheritdoc />
+ public void Dispose()
+ {
+ if (_disposed)
{
- Triggered?.Invoke(this, EventArgs.Empty);
+ return;
}
- /// <inheritdoc />
- public void Dispose()
- {
- if (_disposed)
- {
- return;
- }
-
- DisposeTimer();
+ DisposeTimer();
- _disposed = true;
- }
+ _disposed = true;
}
}
diff --git a/Emby.Server.Implementations/ServerApplicationPaths.cs b/Emby.Server.Implementations/ServerApplicationPaths.cs
index 725df98da..f049e6647 100644
--- a/Emby.Server.Implementations/ServerApplicationPaths.cs
+++ b/Emby.Server.Implementations/ServerApplicationPaths.cs
@@ -96,5 +96,12 @@ namespace Emby.Server.Implementations
/// <inheritdoc />
public string VirtualInternalMetadataPath => "%MetadataPath%";
+
+ /// <inheritdoc/>
+ public override void MakeSanityCheckOrThrow()
+ {
+ base.MakeSanityCheckOrThrow();
+ CreateAndCheckMarker(RootFolderPath, "root");
+ }
}
}
diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs
index ac3e10594..8cbd957a8 100644
--- a/Emby.Server.Implementations/Session/SessionManager.cs
+++ b/Emby.Server.Implementations/Session/SessionManager.cs
@@ -508,13 +508,11 @@ namespace Emby.Server.Implementations.Session
ArgumentException.ThrowIfNullOrEmpty(deviceId);
var key = GetSessionKey(appName, deviceId);
-
- CheckDisposed();
-
- if (!_activeConnections.TryGetValue(key, out var sessionInfo))
+ SessionInfo newSession = CreateSessionInfo(key, appName, appVersion, deviceId, deviceName, remoteEndPoint, user);
+ SessionInfo sessionInfo = _activeConnections.GetOrAdd(key, newSession);
+ if (ReferenceEquals(newSession, sessionInfo))
{
- sessionInfo = CreateSession(key, appName, appVersion, deviceId, deviceName, remoteEndPoint, user);
- _activeConnections[key] = sessionInfo;
+ OnSessionStarted(newSession);
}
sessionInfo.UserId = user?.Id ?? Guid.Empty;
@@ -538,7 +536,7 @@ namespace Emby.Server.Implementations.Session
return sessionInfo;
}
- private SessionInfo CreateSession(
+ private SessionInfo CreateSessionInfo(
string key,
string appName,
string appVersion,
@@ -582,7 +580,6 @@ namespace Emby.Server.Implementations.Session
sessionInfo.HasCustomDeviceName = true;
}
- OnSessionStarted(sessionInfo);
return sessionInfo;
}
@@ -1808,7 +1805,6 @@ namespace Emby.Server.Implementations.Session
fields.Remove(ItemFields.DateLastSaved);
fields.Remove(ItemFields.DisplayPreferencesId);
fields.Remove(ItemFields.Etag);
- fields.Remove(ItemFields.InheritedParentalRatingValue);
fields.Remove(ItemFields.ItemCounts);
fields.Remove(ItemFields.MediaSourceCount);
fields.Remove(ItemFields.MediaStreams);
diff --git a/Emby.Server.Implementations/Sorting/DateLastMediaAddedComparer.cs b/Emby.Server.Implementations/Sorting/DateLastMediaAddedComparer.cs
index 9afc51108..f10e7fcbb 100644
--- a/Emby.Server.Implementations/Sorting/DateLastMediaAddedComparer.cs
+++ b/Emby.Server.Implementations/Sorting/DateLastMediaAddedComparer.cs
@@ -26,10 +26,10 @@ namespace Emby.Server.Implementations.Sorting
public IUserManager UserManager { get; set; }
/// <summary>
- /// Gets or sets the user data repository.
+ /// Gets or sets the user data manager.
/// </summary>
- /// <value>The user data repository.</value>
- public IUserDataManager UserDataRepository { get; set; }
+ /// <value>The user data manager.</value>
+ public IUserDataManager UserDataManager { get; set; }
/// <summary>
/// Gets the name.
diff --git a/Emby.Server.Implementations/Sorting/DatePlayedComparer.cs b/Emby.Server.Implementations/Sorting/DatePlayedComparer.cs
index 4c013a8bd..2c8e2b37d 100644
--- a/Emby.Server.Implementations/Sorting/DatePlayedComparer.cs
+++ b/Emby.Server.Implementations/Sorting/DatePlayedComparer.cs
@@ -28,10 +28,10 @@ namespace Emby.Server.Implementations.Sorting
public IUserManager UserManager { get; set; }
/// <summary>
- /// Gets or sets the user data repository.
+ /// Gets or sets the user data manager.
/// </summary>
- /// <value>The user data repository.</value>
- public IUserDataManager UserDataRepository { get; set; }
+ /// <value>The user data manager.</value>
+ public IUserDataManager UserDataManager { get; set; }
/// <summary>
/// Gets the name.
@@ -57,7 +57,7 @@ namespace Emby.Server.Implementations.Sorting
/// <returns>DateTime.</returns>
private DateTime GetDate(BaseItem x)
{
- var userdata = UserDataRepository.GetUserData(User, x);
+ var userdata = UserDataManager.GetUserData(User, x);
if (userdata is not null && userdata.LastPlayedDate.HasValue)
{
diff --git a/Emby.Server.Implementations/Sorting/IsFavoriteOrLikeComparer.cs b/Emby.Server.Implementations/Sorting/IsFavoriteOrLikeComparer.cs
index cf7786167..01c1e596f 100644
--- a/Emby.Server.Implementations/Sorting/IsFavoriteOrLikeComparer.cs
+++ b/Emby.Server.Implementations/Sorting/IsFavoriteOrLikeComparer.cs
@@ -25,10 +25,10 @@ namespace Emby.Server.Implementations.Sorting
public ItemSortBy Type => ItemSortBy.IsFavoriteOrLiked;
/// <summary>
- /// Gets or sets the user data repository.
+ /// Gets or sets the user data manager.
/// </summary>
- /// <value>The user data repository.</value>
- public IUserDataManager UserDataRepository { get; set; }
+ /// <value>The user data manager.</value>
+ public IUserDataManager UserDataManager { get; set; }
/// <summary>
/// Gets or sets the user manager.
diff --git a/Emby.Server.Implementations/Sorting/IsPlayedComparer.cs b/Emby.Server.Implementations/Sorting/IsPlayedComparer.cs
index e42c8a33a..6f206c877 100644
--- a/Emby.Server.Implementations/Sorting/IsPlayedComparer.cs
+++ b/Emby.Server.Implementations/Sorting/IsPlayedComparer.cs
@@ -26,10 +26,10 @@ namespace Emby.Server.Implementations.Sorting
public ItemSortBy Type => ItemSortBy.IsUnplayed;
/// <summary>
- /// Gets or sets the user data repository.
+ /// Gets or sets the user data manager.
/// </summary>
- /// <value>The user data repository.</value>
- public IUserDataManager UserDataRepository { get; set; }
+ /// <value>The user data manager.</value>
+ public IUserDataManager UserDataManager { get; set; }
/// <summary>
/// Gets or sets the user manager.
diff --git a/Emby.Server.Implementations/Sorting/IsUnplayedComparer.cs b/Emby.Server.Implementations/Sorting/IsUnplayedComparer.cs
index f54188030..fd1326327 100644
--- a/Emby.Server.Implementations/Sorting/IsUnplayedComparer.cs
+++ b/Emby.Server.Implementations/Sorting/IsUnplayedComparer.cs
@@ -26,10 +26,10 @@ namespace Emby.Server.Implementations.Sorting
public ItemSortBy Type => ItemSortBy.IsUnplayed;
/// <summary>
- /// Gets or sets the user data repository.
+ /// Gets or sets the user data manager.
/// </summary>
- /// <value>The user data repository.</value>
- public IUserDataManager UserDataRepository { get; set; }
+ /// <value>The user data manager.</value>
+ public IUserDataManager UserDataManager { get; set; }
/// <summary>
/// Gets or sets the user manager.
diff --git a/Emby.Server.Implementations/Sorting/OfficialRatingComparer.cs b/Emby.Server.Implementations/Sorting/OfficialRatingComparer.cs
index b4ee2c723..789af01cc 100644
--- a/Emby.Server.Implementations/Sorting/OfficialRatingComparer.cs
+++ b/Emby.Server.Implementations/Sorting/OfficialRatingComparer.cs
@@ -1,45 +1,54 @@
-#pragma warning disable CS1591
-
using System;
using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Sorting;
+using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.Querying;
-namespace Emby.Server.Implementations.Sorting
+namespace Emby.Server.Implementations.Sorting;
+
+/// <summary>
+/// Class providing comparison for official ratings.
+/// </summary>
+public class OfficialRatingComparer : IBaseItemComparer
{
- public class OfficialRatingComparer : IBaseItemComparer
+ private readonly ILocalizationManager _localizationManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OfficialRatingComparer"/> class.
+ /// </summary>
+ /// <param name="localizationManager">Instance of the <see cref="ILocalizationManager"/> interface.</param>
+ public OfficialRatingComparer(ILocalizationManager localizationManager)
{
- private readonly ILocalizationManager _localization;
+ _localizationManager = localizationManager;
+ }
- public OfficialRatingComparer(ILocalizationManager localization)
+ /// <summary>
+ /// Gets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public ItemSortBy Type => ItemSortBy.OfficialRating;
+
+ /// <summary>
+ /// Compares the specified x.
+ /// </summary>
+ /// <param name="x">The x.</param>
+ /// <param name="y">The y.</param>
+ /// <returns>System.Int32.</returns>
+ public int Compare(BaseItem? x, BaseItem? y)
+ {
+ ArgumentNullException.ThrowIfNull(x);
+ ArgumentNullException.ThrowIfNull(y);
+ var zeroRating = new ParentalRatingScore(0, 0);
+
+ var ratingX = string.IsNullOrEmpty(x.OfficialRating) ? zeroRating : _localizationManager.GetRatingScore(x.OfficialRating) ?? zeroRating;
+ var ratingY = string.IsNullOrEmpty(y.OfficialRating) ? zeroRating : _localizationManager.GetRatingScore(y.OfficialRating) ?? zeroRating;
+ var scoreCompare = ratingX.Score.CompareTo(ratingY.Score);
+ if (scoreCompare is 0)
{
- _localization = localization;
+ return (ratingX.SubScore ?? 0).CompareTo(ratingY.SubScore ?? 0);
}
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- public ItemSortBy Type => ItemSortBy.OfficialRating;
-
- /// <summary>
- /// Compares the specified x.
- /// </summary>
- /// <param name="x">The x.</param>
- /// <param name="y">The y.</param>
- /// <returns>System.Int32.</returns>
- public int Compare(BaseItem? x, BaseItem? y)
- {
- ArgumentNullException.ThrowIfNull(x);
-
- ArgumentNullException.ThrowIfNull(y);
-
- var levelX = string.IsNullOrEmpty(x.OfficialRating) ? 0 : _localization.GetRatingLevel(x.OfficialRating) ?? 0;
- var levelY = string.IsNullOrEmpty(y.OfficialRating) ? 0 : _localization.GetRatingLevel(y.OfficialRating) ?? 0;
-
- return levelX.CompareTo(levelY);
- }
+ return scoreCompare;
}
}
diff --git a/Emby.Server.Implementations/Sorting/PlayCountComparer.cs b/Emby.Server.Implementations/Sorting/PlayCountComparer.cs
index dd2149b57..26e28b03b 100644
--- a/Emby.Server.Implementations/Sorting/PlayCountComparer.cs
+++ b/Emby.Server.Implementations/Sorting/PlayCountComparer.cs
@@ -27,10 +27,10 @@ namespace Emby.Server.Implementations.Sorting
public ItemSortBy Type => ItemSortBy.PlayCount;
/// <summary>
- /// Gets or sets the user data repository.
+ /// Gets or sets the user data manager.
/// </summary>
- /// <value>The user data repository.</value>
- public IUserDataManager UserDataRepository { get; set; }
+ /// <value>The user data manager.</value>
+ public IUserDataManager UserDataManager { get; set; }
/// <summary>
/// Gets or sets the user manager.
@@ -56,7 +56,7 @@ namespace Emby.Server.Implementations.Sorting
/// <returns>DateTime.</returns>
private int GetValue(BaseItem x)
{
- var userdata = UserDataRepository.GetUserData(User, x);
+ var userdata = UserDataManager.GetUserData(User, x);
return userdata is null ? 0 : userdata.PlayCount;
}
diff --git a/Emby.Server.Implementations/SyncPlay/Group.cs b/Emby.Server.Implementations/SyncPlay/Group.cs
index d47e47793..c2e834ad5 100644
--- a/Emby.Server.Implementations/SyncPlay/Group.cs
+++ b/Emby.Server.Implementations/SyncPlay/Group.cs
@@ -273,7 +273,7 @@ namespace Emby.Server.Implementations.SyncPlay
SetState(waitingState);
}
- var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, GetInfo());
+ var updateSession = new SyncPlayGroupJoinedUpdate(GroupId, GetInfo());
SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken);
_state.SessionJoined(this, _state.Type, session, cancellationToken);
@@ -291,10 +291,10 @@ namespace Emby.Server.Implementations.SyncPlay
{
AddSession(session);
- var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, GetInfo());
+ var updateSession = new SyncPlayGroupJoinedUpdate(GroupId, GetInfo());
SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken);
- var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserJoined, session.UserName);
+ var updateOthers = new SyncPlayUserJoinedUpdate(GroupId, session.UserName);
SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken);
_state.SessionJoined(this, _state.Type, session, cancellationToken);
@@ -314,10 +314,10 @@ namespace Emby.Server.Implementations.SyncPlay
RemoveSession(session);
- var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupLeft, GroupId.ToString());
+ var updateSession = new SyncPlayGroupLeftUpdate(GroupId, GroupId.ToString());
SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken);
- var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserLeft, session.UserName);
+ var updateOthers = new SyncPlayUserLeftUpdate(GroupId, session.UserName);
SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken);
_logger.LogInformation("Session {SessionId} left group {GroupId}.", session.Id, GroupId.ToString());
@@ -426,12 +426,6 @@ namespace Emby.Server.Implementations.SyncPlay
}
/// <inheritdoc />
- public GroupUpdate<T> NewSyncPlayGroupUpdate<T>(GroupUpdateType type, T data)
- {
- return new GroupUpdate<T>(GroupId, type, data);
- }
-
- /// <inheritdoc />
public long SanitizePositionTicks(long? positionTicks)
{
var ticks = positionTicks ?? 0;
diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs
index fdfff8f3b..b45d75455 100644
--- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs
+++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs
@@ -100,7 +100,7 @@ namespace Emby.Server.Implementations.SyncPlay
}
/// <inheritdoc />
- public void NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken)
+ public GroupInfoDto NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken)
{
if (session is null)
{
@@ -132,6 +132,7 @@ namespace Emby.Server.Implementations.SyncPlay
UpdateSessionsCounter(session.UserId, 1);
group.CreateGroup(session, request, cancellationToken);
+ return group.GetInfo();
}
}
@@ -159,7 +160,7 @@ namespace Emby.Server.Implementations.SyncPlay
{
_logger.LogWarning("Session {SessionId} tried to join group {GroupId} that does not exist.", session.Id, request.GroupId);
- var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.GroupDoesNotExist, string.Empty);
+ var error = new SyncPlayGroupDoesNotExistUpdate(Guid.Empty, string.Empty);
_sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None);
return;
}
@@ -171,7 +172,7 @@ namespace Emby.Server.Implementations.SyncPlay
{
_logger.LogWarning("Session {SessionId} tried to join group {GroupId} but does not have access to some content of the playing queue.", session.Id, group.GroupId.ToString());
- var error = new GroupUpdate<string>(group.GroupId, GroupUpdateType.LibraryAccessDenied, string.Empty);
+ var error = new SyncPlayLibraryAccessDeniedUpdate(group.GroupId, string.Empty);
_sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None);
return;
}
@@ -248,7 +249,7 @@ namespace Emby.Server.Implementations.SyncPlay
{
_logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id);
- var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty);
+ var error = new SyncPlayNotInGroupUpdate(Guid.Empty, string.Empty);
_sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None);
}
}
@@ -289,6 +290,31 @@ namespace Emby.Server.Implementations.SyncPlay
}
/// <inheritdoc />
+ public GroupInfoDto GetGroup(SessionInfo session, Guid groupId)
+ {
+ ArgumentNullException.ThrowIfNull(session);
+
+ var user = _userManager.GetUserById(session.UserId);
+
+ lock (_groupsLock)
+ {
+ foreach (var (_, group) in _groups)
+ {
+ // Locking required as group is not thread-safe.
+ lock (group)
+ {
+ if (group.GroupId.Equals(groupId) && group.HasAccessToPlayQueue(user))
+ {
+ return group.GetInfo();
+ }
+ }
+ }
+ }
+
+ return null;
+ }
+
+ /// <inheritdoc />
public void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken)
{
if (session is null)
@@ -327,7 +353,7 @@ namespace Emby.Server.Implementations.SyncPlay
{
_logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id);
- var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty);
+ var error = new SyncPlayNotInGroupUpdate(Guid.Empty, string.Empty);
_sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None);
}
}
diff --git a/Emby.Server.Implementations/SystemManager.cs b/Emby.Server.Implementations/SystemManager.cs
index c4552474c..92b59b23c 100644
--- a/Emby.Server.Implementations/SystemManager.cs
+++ b/Emby.Server.Implementations/SystemManager.cs
@@ -1,9 +1,12 @@
+using System;
using System.Linq;
using System.Threading.Tasks;
+using Jellyfin.Server.Implementations.StorageHelpers;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Updates;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Library;
using MediaBrowser.Model.System;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
@@ -19,6 +22,7 @@ public class SystemManager : ISystemManager
private readonly IServerConfigurationManager _configurationManager;
private readonly IStartupOptions _startupOptions;
private readonly IInstallationManager _installationManager;
+ private readonly ILibraryManager _libraryManager;
/// <summary>
/// Initializes a new instance of the <see cref="SystemManager"/> class.
@@ -29,13 +33,15 @@ public class SystemManager : ISystemManager
/// <param name="configurationManager">Instance of <see cref="IServerConfigurationManager"/>.</param>
/// <param name="startupOptions">Instance of <see cref="IStartupOptions"/>.</param>
/// <param name="installationManager">Instance of <see cref="IInstallationManager"/>.</param>
+ /// <param name="libraryManager">Instance of <see cref="ILibraryManager"/>.</param>
public SystemManager(
IHostApplicationLifetime applicationLifetime,
IServerApplicationHost applicationHost,
IServerApplicationPaths applicationPaths,
IServerConfigurationManager configurationManager,
IStartupOptions startupOptions,
- IInstallationManager installationManager)
+ IInstallationManager installationManager,
+ ILibraryManager libraryManager)
{
_applicationLifetime = applicationLifetime;
_applicationHost = applicationHost;
@@ -43,6 +49,7 @@ public class SystemManager : ISystemManager
_configurationManager = configurationManager;
_startupOptions = startupOptions;
_installationManager = installationManager;
+ _libraryManager = libraryManager;
}
/// <inheritdoc />
@@ -53,9 +60,11 @@ public class SystemManager : ISystemManager
HasPendingRestart = _applicationHost.HasPendingRestart,
IsShuttingDown = _applicationLifetime.ApplicationStopping.IsCancellationRequested,
Version = _applicationHost.ApplicationVersionString,
+ ProductName = _applicationHost.Name,
WebSocketPortNumber = _applicationHost.HttpPort,
CompletedInstallations = _installationManager.CompletedInstallations.ToArray(),
Id = _applicationHost.SystemId,
+#pragma warning disable CS0618 // Type or member is obsolete
ProgramDataPath = _applicationPaths.ProgramDataPath,
WebPath = _applicationPaths.WebPath,
LogPath = _applicationPaths.LogDirectoryPath,
@@ -63,14 +72,39 @@ public class SystemManager : ISystemManager
InternalMetadataPath = _applicationPaths.InternalMetadataPath,
CachePath = _applicationPaths.CachePath,
TranscodingTempPath = _configurationManager.GetTranscodePath(),
+#pragma warning restore CS0618 // Type or member is obsolete
ServerName = _applicationHost.FriendlyName,
LocalAddress = _applicationHost.GetSmartApiUrl(request),
+ StartupWizardCompleted = _configurationManager.CommonConfiguration.IsStartupWizardCompleted,
SupportsLibraryMonitor = true,
PackageName = _startupOptions.PackageName,
CastReceiverApplications = _configurationManager.Configuration.CastReceiverApplications
};
}
+ /// <inheritdoc/>
+ public SystemStorageInfo GetSystemStorageInfo()
+ {
+ var virtualFolderInfos = _libraryManager.GetVirtualFolders().Select(e => new LibraryStorageInfo()
+ {
+ Id = Guid.Parse(e.ItemId),
+ Name = e.Name,
+ Folders = e.Locations.Select(f => StorageHelper.GetFreeSpaceOf(f)).ToArray()
+ });
+
+ return new SystemStorageInfo()
+ {
+ ProgramDataFolder = StorageHelper.GetFreeSpaceOf(_applicationPaths.ProgramDataPath),
+ WebFolder = StorageHelper.GetFreeSpaceOf(_applicationPaths.WebPath),
+ LogFolder = StorageHelper.GetFreeSpaceOf(_applicationPaths.LogDirectoryPath),
+ ImageCacheFolder = StorageHelper.GetFreeSpaceOf(_applicationPaths.ImageCachePath),
+ InternalMetadataFolder = StorageHelper.GetFreeSpaceOf(_applicationPaths.InternalMetadataPath),
+ CacheFolder = StorageHelper.GetFreeSpaceOf(_applicationPaths.CachePath),
+ TranscodingTempFolder = StorageHelper.GetFreeSpaceOf(_configurationManager.GetTranscodePath()),
+ Libraries = virtualFolderInfos.ToArray()
+ };
+ }
+
/// <inheritdoc />
public PublicSystemInfo GetPublicSystemInfo(HttpRequest request)
{
diff --git a/Jellyfin.Api/Controllers/AudioController.cs b/Jellyfin.Api/Controllers/AudioController.cs
index 272b4034e..e334e1264 100644
--- a/Jellyfin.Api/Controllers/AudioController.cs
+++ b/Jellyfin.Api/Controllers/AudioController.cs
@@ -92,18 +92,18 @@ public class AudioController : BaseJellyfinApiController
[ProducesAudioFile]
public async Task<ActionResult> GetAudioStream(
[FromRoute, Required] Guid itemId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? container,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? container,
[FromQuery] bool? @static,
[FromQuery] string? @params,
[FromQuery] string? tag,
[FromQuery, ParameterObsolete] string? deviceProfileId,
[FromQuery] string? playSessionId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? segmentContainer,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
[FromQuery] int? segmentLength,
[FromQuery] int? minSegments,
[FromQuery] string? mediaSourceId,
[FromQuery] string? deviceId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
[FromQuery] bool? enableAutoStreamCopy,
[FromQuery] bool? allowVideoStreamCopy,
[FromQuery] bool? allowAudioStreamCopy,
@@ -114,7 +114,7 @@ public class AudioController : BaseJellyfinApiController
[FromQuery] int? audioChannels,
[FromQuery] int? maxAudioChannels,
[FromQuery] string? profile,
- [FromQuery] string? level,
+ [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
[FromQuery] float? framerate,
[FromQuery] float? maxFramerate,
[FromQuery] bool? copyTimestamps,
@@ -133,8 +133,8 @@ public class AudioController : BaseJellyfinApiController
[FromQuery] int? cpuCoreLimit,
[FromQuery] string? liveStreamId,
[FromQuery] bool? enableMpegtsM2TsMode,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? videoCodec,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? subtitleCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
[FromQuery] string? transcodeReasons,
[FromQuery] int? audioStreamIndex,
[FromQuery] int? videoStreamIndex,
@@ -259,18 +259,18 @@ public class AudioController : BaseJellyfinApiController
[ProducesAudioFile]
public async Task<ActionResult> GetAudioStreamByContainer(
[FromRoute, Required] Guid itemId,
- [FromRoute, Required] string container,
+ [FromRoute, Required] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string container,
[FromQuery] bool? @static,
[FromQuery] string? @params,
[FromQuery] string? tag,
[FromQuery, ParameterObsolete] string? deviceProfileId,
[FromQuery] string? playSessionId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? segmentContainer,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
[FromQuery] int? segmentLength,
[FromQuery] int? minSegments,
[FromQuery] string? mediaSourceId,
[FromQuery] string? deviceId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
[FromQuery] bool? enableAutoStreamCopy,
[FromQuery] bool? allowVideoStreamCopy,
[FromQuery] bool? allowAudioStreamCopy,
@@ -281,7 +281,7 @@ public class AudioController : BaseJellyfinApiController
[FromQuery] int? audioChannels,
[FromQuery] int? maxAudioChannels,
[FromQuery] string? profile,
- [FromQuery] string? level,
+ [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
[FromQuery] float? framerate,
[FromQuery] float? maxFramerate,
[FromQuery] bool? copyTimestamps,
@@ -300,8 +300,8 @@ public class AudioController : BaseJellyfinApiController
[FromQuery] int? cpuCoreLimit,
[FromQuery] string? liveStreamId,
[FromQuery] bool? enableMpegtsM2TsMode,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? videoCodec,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? subtitleCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
[FromQuery] string? transcodeReasons,
[FromQuery] int? audioStreamIndex,
[FromQuery] int? videoStreamIndex,
diff --git a/Jellyfin.Api/Controllers/BackupController.cs b/Jellyfin.Api/Controllers/BackupController.cs
new file mode 100644
index 000000000..aa908ee30
--- /dev/null
+++ b/Jellyfin.Api/Controllers/BackupController.cs
@@ -0,0 +1,127 @@
+using System.IO;
+using System.Threading.Tasks;
+using Jellyfin.Server.Implementations.SystemBackupService;
+using MediaBrowser.Common.Api;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.SystemBackupService;
+using Microsoft.AspNetCore.Authentication.OAuth.Claims;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+
+namespace Jellyfin.Api.Controllers;
+
+/// <summary>
+/// The backup controller.
+/// </summary>
+[Authorize(Policy = Policies.RequiresElevation)]
+public class BackupController : BaseJellyfinApiController
+{
+ private readonly IBackupService _backupService;
+ private readonly IApplicationPaths _applicationPaths;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BackupController"/> class.
+ /// </summary>
+ /// <param name="backupService">Instance of the <see cref="IBackupService"/> interface.</param>
+ /// <param name="applicationPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
+ public BackupController(IBackupService backupService, IApplicationPaths applicationPaths)
+ {
+ _backupService = backupService;
+ _applicationPaths = applicationPaths;
+ }
+
+ /// <summary>
+ /// Creates a new Backup.
+ /// </summary>
+ /// <param name="backupOptions">The backup options.</param>
+ /// <response code="200">Backup created.</response>
+ /// <response code="403">User does not have permission to retrieve information.</response>
+ /// <returns>The created backup manifest.</returns>
+ [HttpPost("Create")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ public async Task<ActionResult<BackupManifestDto>> CreateBackup([FromBody] BackupOptionsDto backupOptions)
+ {
+ return Ok(await _backupService.CreateBackupAsync(backupOptions ?? new()).ConfigureAwait(false));
+ }
+
+ /// <summary>
+ /// Restores to a backup by restarting the server and applying the backup.
+ /// </summary>
+ /// <param name="archiveRestoreDto">The data to start a restore process.</param>
+ /// <response code="204">Backup restore started.</response>
+ /// <response code="403">User does not have permission to retrieve information.</response>
+ /// <returns>No-Content.</returns>
+ [HttpPost("Restore")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ public IActionResult StartRestoreBackup([FromBody, BindRequired] BackupRestoreRequestDto archiveRestoreDto)
+ {
+ var archivePath = SanitizePath(archiveRestoreDto.ArchiveFileName);
+ if (!System.IO.File.Exists(archivePath))
+ {
+ return NotFound();
+ }
+
+ _backupService.ScheduleRestoreAndRestartServer(archivePath);
+ return NoContent();
+ }
+
+ /// <summary>
+ /// Gets a list of all currently present backups in the backup directory.
+ /// </summary>
+ /// <response code="200">Backups available.</response>
+ /// <response code="403">User does not have permission to retrieve information.</response>
+ /// <returns>The list of backups.</returns>
+ [HttpGet]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ public async Task<ActionResult<BackupManifestDto[]>> ListBackups()
+ {
+ return Ok(await _backupService.EnumerateBackups().ConfigureAwait(false));
+ }
+
+ /// <summary>
+ /// Gets the descriptor from an existing archive is present.
+ /// </summary>
+ /// <param name="path">The data to start a restore process.</param>
+ /// <response code="200">Backup archive manifest.</response>
+ /// <response code="204">Not a valid jellyfin Archive.</response>
+ /// <response code="404">Not a valid path.</response>
+ /// <response code="403">User does not have permission to retrieve information.</response>
+ /// <returns>The backup manifest.</returns>
+ [HttpGet("Manifest")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ public async Task<ActionResult<BackupManifestDto>> GetBackup([BindRequired] string path)
+ {
+ var backupPath = SanitizePath(path);
+
+ if (!System.IO.File.Exists(backupPath))
+ {
+ return NotFound();
+ }
+
+ var manifest = await _backupService.GetBackupManifest(backupPath).ConfigureAwait(false);
+ if (manifest is null)
+ {
+ return NoContent();
+ }
+
+ return Ok(manifest);
+ }
+
+ [NonAction]
+ private string SanitizePath(string path)
+ {
+ // sanitize path
+ var archiveRestorePath = Path.GetFileName(Path.GetFullPath(path));
+ var archivePath = Path.Combine(_applicationPaths.BackupPath, archiveRestorePath);
+ return archivePath;
+ }
+}
diff --git a/Jellyfin.Api/Controllers/BrandingController.cs b/Jellyfin.Api/Controllers/BrandingController.cs
index 3c2c4b4db..1d948ff20 100644
--- a/Jellyfin.Api/Controllers/BrandingController.cs
+++ b/Jellyfin.Api/Controllers/BrandingController.cs
@@ -29,9 +29,18 @@ public class BrandingController : BaseJellyfinApiController
/// <returns>An <see cref="OkResult"/> containing the branding configuration.</returns>
[HttpGet("Configuration")]
[ProducesResponseType(StatusCodes.Status200OK)]
- public ActionResult<BrandingOptions> GetBrandingOptions()
+ public ActionResult<BrandingOptionsDto> GetBrandingOptions()
{
- return _serverConfigurationManager.GetConfiguration<BrandingOptions>("branding");
+ var brandingOptions = _serverConfigurationManager.GetConfiguration<BrandingOptions>("branding");
+
+ var brandingOptionsDto = new BrandingOptionsDto
+ {
+ LoginDisclaimer = brandingOptions.LoginDisclaimer,
+ CustomCss = brandingOptions.CustomCss,
+ SplashscreenEnabled = brandingOptions.SplashscreenEnabled
+ };
+
+ return brandingOptionsDto;
}
/// <summary>
diff --git a/Jellyfin.Api/Controllers/ConfigurationController.cs b/Jellyfin.Api/Controllers/ConfigurationController.cs
index abe8bec2d..8dcaebf6d 100644
--- a/Jellyfin.Api/Controllers/ConfigurationController.cs
+++ b/Jellyfin.Api/Controllers/ConfigurationController.cs
@@ -9,6 +9,7 @@ using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Api;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Model.Branding;
using MediaBrowser.Model.Configuration;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
@@ -120,6 +121,30 @@ public class ConfigurationController : BaseJellyfinApiController
}
/// <summary>
+ /// Updates branding configuration.
+ /// </summary>
+ /// <param name="configuration">Branding configuration.</param>
+ /// <response code="204">Branding configuration updated.</response>
+ /// <returns>Update status.</returns>
+ [HttpPost("Configuration/Branding")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult UpdateBrandingConfiguration([FromBody, Required] BrandingOptionsDto configuration)
+ {
+ // Get the current branding configuration to preserve SplashscreenLocation
+ var currentBranding = (BrandingOptions)_configurationManager.GetConfiguration("branding");
+
+ // Update only the properties from BrandingOptionsDto
+ currentBranding.LoginDisclaimer = configuration.LoginDisclaimer;
+ currentBranding.CustomCss = configuration.CustomCss;
+ currentBranding.SplashscreenEnabled = configuration.SplashscreenEnabled;
+
+ _configurationManager.SaveConfiguration("branding", currentBranding);
+
+ return NoContent();
+ }
+
+ /// <summary>
/// Updates the path to the media encoder.
/// </summary>
/// <param name="mediaEncoderPath">Media encoder path form body.</param>
diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs
index ca8ab0ef7..4cac8ed67 100644
--- a/Jellyfin.Api/Controllers/DynamicHlsController.cs
+++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs
@@ -166,18 +166,18 @@ public class DynamicHlsController : BaseJellyfinApiController
[ProducesPlaylistFile]
public async Task<ActionResult> GetLiveHlsStream(
[FromRoute, Required] Guid itemId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? container,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? container,
[FromQuery] bool? @static,
[FromQuery] string? @params,
[FromQuery] string? tag,
[FromQuery, ParameterObsolete] string? deviceProfileId,
[FromQuery] string? playSessionId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? segmentContainer,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
[FromQuery] int? segmentLength,
[FromQuery] int? minSegments,
[FromQuery] string? mediaSourceId,
[FromQuery] string? deviceId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
[FromQuery] bool? enableAutoStreamCopy,
[FromQuery] bool? allowVideoStreamCopy,
[FromQuery] bool? allowAudioStreamCopy,
@@ -188,7 +188,7 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] int? audioChannels,
[FromQuery] int? maxAudioChannels,
[FromQuery] string? profile,
- [FromQuery] string? level,
+ [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
[FromQuery] float? framerate,
[FromQuery] float? maxFramerate,
[FromQuery] bool? copyTimestamps,
@@ -207,8 +207,8 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] int? cpuCoreLimit,
[FromQuery] string? liveStreamId,
[FromQuery] bool? enableMpegtsM2TsMode,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? videoCodec,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? subtitleCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
[FromQuery] string? transcodeReasons,
[FromQuery] int? audioStreamIndex,
[FromQuery] int? videoStreamIndex,
@@ -415,12 +415,12 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] string? tag,
[FromQuery, ParameterObsolete] string? deviceProfileId,
[FromQuery] string? playSessionId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? segmentContainer,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
[FromQuery] int? segmentLength,
[FromQuery] int? minSegments,
[FromQuery, Required] string mediaSourceId,
[FromQuery] string? deviceId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
[FromQuery] bool? enableAutoStreamCopy,
[FromQuery] bool? allowVideoStreamCopy,
[FromQuery] bool? allowAudioStreamCopy,
@@ -431,7 +431,7 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] int? audioChannels,
[FromQuery] int? maxAudioChannels,
[FromQuery] string? profile,
- [FromQuery] string? level,
+ [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
[FromQuery] float? framerate,
[FromQuery] float? maxFramerate,
[FromQuery] bool? copyTimestamps,
@@ -452,8 +452,8 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] int? cpuCoreLimit,
[FromQuery] string? liveStreamId,
[FromQuery] bool? enableMpegtsM2TsMode,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? videoCodec,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? subtitleCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
[FromQuery] string? transcodeReasons,
[FromQuery] int? audioStreamIndex,
[FromQuery] int? videoStreamIndex,
@@ -591,12 +591,12 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] string? tag,
[FromQuery, ParameterObsolete] string? deviceProfileId,
[FromQuery] string? playSessionId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? segmentContainer,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
[FromQuery] int? segmentLength,
[FromQuery] int? minSegments,
[FromQuery, Required] string mediaSourceId,
[FromQuery] string? deviceId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
[FromQuery] bool? enableAutoStreamCopy,
[FromQuery] bool? allowVideoStreamCopy,
[FromQuery] bool? allowAudioStreamCopy,
@@ -608,7 +608,7 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] int? audioChannels,
[FromQuery] int? maxAudioChannels,
[FromQuery] string? profile,
- [FromQuery] string? level,
+ [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
[FromQuery] float? framerate,
[FromQuery] float? maxFramerate,
[FromQuery] bool? copyTimestamps,
@@ -627,8 +627,8 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] int? cpuCoreLimit,
[FromQuery] string? liveStreamId,
[FromQuery] bool? enableMpegtsM2TsMode,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? videoCodec,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? subtitleCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
[FromQuery] string? transcodeReasons,
[FromQuery] int? audioStreamIndex,
[FromQuery] int? videoStreamIndex,
@@ -761,12 +761,12 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] string? tag,
[FromQuery, ParameterObsolete] string? deviceProfileId,
[FromQuery] string? playSessionId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? segmentContainer,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
[FromQuery] int? segmentLength,
[FromQuery] int? minSegments,
[FromQuery] string? mediaSourceId,
[FromQuery] string? deviceId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
[FromQuery] bool? enableAutoStreamCopy,
[FromQuery] bool? allowVideoStreamCopy,
[FromQuery] bool? allowAudioStreamCopy,
@@ -777,7 +777,7 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] int? audioChannels,
[FromQuery] int? maxAudioChannels,
[FromQuery] string? profile,
- [FromQuery] string? level,
+ [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
[FromQuery] float? framerate,
[FromQuery] float? maxFramerate,
[FromQuery] bool? copyTimestamps,
@@ -798,8 +798,8 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] int? cpuCoreLimit,
[FromQuery] string? liveStreamId,
[FromQuery] bool? enableMpegtsM2TsMode,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? videoCodec,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? subtitleCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
[FromQuery] string? transcodeReasons,
[FromQuery] int? audioStreamIndex,
[FromQuery] int? videoStreamIndex,
@@ -933,12 +933,12 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] string? tag,
[FromQuery, ParameterObsolete] string? deviceProfileId,
[FromQuery] string? playSessionId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? segmentContainer,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
[FromQuery] int? segmentLength,
[FromQuery] int? minSegments,
[FromQuery] string? mediaSourceId,
[FromQuery] string? deviceId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
[FromQuery] bool? enableAutoStreamCopy,
[FromQuery] bool? allowVideoStreamCopy,
[FromQuery] bool? allowAudioStreamCopy,
@@ -950,7 +950,7 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] int? audioChannels,
[FromQuery] int? maxAudioChannels,
[FromQuery] string? profile,
- [FromQuery] string? level,
+ [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
[FromQuery] float? framerate,
[FromQuery] float? maxFramerate,
[FromQuery] bool? copyTimestamps,
@@ -969,8 +969,8 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] int? cpuCoreLimit,
[FromQuery] string? liveStreamId,
[FromQuery] bool? enableMpegtsM2TsMode,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? videoCodec,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? subtitleCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
[FromQuery] string? transcodeReasons,
[FromQuery] int? audioStreamIndex,
[FromQuery] int? videoStreamIndex,
@@ -1106,7 +1106,7 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromRoute, Required] Guid itemId,
[FromRoute, Required] string playlistId,
[FromRoute, Required] int segmentId,
- [FromRoute, Required] string container,
+ [FromRoute, Required] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string container,
[FromQuery, Required] long runtimeTicks,
[FromQuery, Required] long actualSegmentLengthTicks,
[FromQuery] bool? @static,
@@ -1114,12 +1114,12 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] string? tag,
[FromQuery, ParameterObsolete] string? deviceProfileId,
[FromQuery] string? playSessionId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? segmentContainer,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
[FromQuery] int? segmentLength,
[FromQuery] int? minSegments,
[FromQuery] string? mediaSourceId,
[FromQuery] string? deviceId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
[FromQuery] bool? enableAutoStreamCopy,
[FromQuery] bool? allowVideoStreamCopy,
[FromQuery] bool? allowAudioStreamCopy,
@@ -1130,7 +1130,7 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] int? audioChannels,
[FromQuery] int? maxAudioChannels,
[FromQuery] string? profile,
- [FromQuery] string? level,
+ [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
[FromQuery] float? framerate,
[FromQuery] float? maxFramerate,
[FromQuery] bool? copyTimestamps,
@@ -1151,8 +1151,8 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] int? cpuCoreLimit,
[FromQuery] string? liveStreamId,
[FromQuery] bool? enableMpegtsM2TsMode,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? videoCodec,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? subtitleCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
[FromQuery] string? transcodeReasons,
[FromQuery] int? audioStreamIndex,
[FromQuery] int? videoStreamIndex,
@@ -1291,7 +1291,7 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromRoute, Required] Guid itemId,
[FromRoute, Required] string playlistId,
[FromRoute, Required] int segmentId,
- [FromRoute, Required] string container,
+ [FromRoute, Required] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string container,
[FromQuery, Required] long runtimeTicks,
[FromQuery, Required] long actualSegmentLengthTicks,
[FromQuery] bool? @static,
@@ -1299,12 +1299,12 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] string? tag,
[FromQuery, ParameterObsolete] string? deviceProfileId,
[FromQuery] string? playSessionId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? segmentContainer,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
[FromQuery] int? segmentLength,
[FromQuery] int? minSegments,
[FromQuery] string? mediaSourceId,
[FromQuery] string? deviceId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
[FromQuery] bool? enableAutoStreamCopy,
[FromQuery] bool? allowVideoStreamCopy,
[FromQuery] bool? allowAudioStreamCopy,
@@ -1316,7 +1316,7 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] int? audioChannels,
[FromQuery] int? maxAudioChannels,
[FromQuery] string? profile,
- [FromQuery] string? level,
+ [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
[FromQuery] float? framerate,
[FromQuery] float? maxFramerate,
[FromQuery] bool? copyTimestamps,
@@ -1335,8 +1335,8 @@ public class DynamicHlsController : BaseJellyfinApiController
[FromQuery] int? cpuCoreLimit,
[FromQuery] string? liveStreamId,
[FromQuery] bool? enableMpegtsM2TsMode,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? videoCodec,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? subtitleCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
[FromQuery] string? transcodeReasons,
[FromQuery] int? audioStreamIndex,
[FromQuery] int? videoStreamIndex,
@@ -1419,8 +1419,9 @@ public class DynamicHlsController : BaseJellyfinApiController
TranscodingJobType,
cancellationTokenSource.Token)
.ConfigureAwait(false);
-
+ var mediaSourceId = state.BaseRequest.MediaSourceId;
var request = new CreateMainPlaylistRequest(
+ mediaSourceId is null ? null : Guid.Parse(mediaSourceId),
state.MediaPath,
state.SegmentLength * 1000,
state.RunTimeTicks ?? 0,
@@ -1675,7 +1676,7 @@ public class DynamicHlsController : BaseJellyfinApiController
}
var audioCodec = _encodingHelper.GetAudioEncoder(state);
- var bitStreamArgs = EncodingHelper.GetAudioBitStreamArguments(state, state.Request.SegmentContainer, state.MediaSource.Container);
+ var bitStreamArgs = _encodingHelper.GetAudioBitStreamArguments(state, state.Request.SegmentContainer, state.MediaSource.Container);
// opus, dts, truehd and flac (in FFmpeg 5 and older) are experimental in mp4 muxer
var strictArgs = string.Empty;
@@ -1753,7 +1754,7 @@ public class DynamicHlsController : BaseJellyfinApiController
if (channels.HasValue
&& (channels.Value != 2
- || (state.AudioStream?.Channels != null && !useDownMixAlgorithm)))
+ || (state.AudioStream?.Channels is not null && !useDownMixAlgorithm)))
{
args += " -ac " + channels.Value;
}
@@ -1822,10 +1823,11 @@ public class DynamicHlsController : BaseJellyfinApiController
// Clients reporting Dolby Vision capabilities with fallbacks may only support the fallback layer.
// Only enable Dolby Vision remuxing if the client explicitly declares support for profiles without fallbacks.
var clientSupportsDoVi = requestedRange.Contains(VideoRangeType.DOVI.ToString(), StringComparison.OrdinalIgnoreCase);
- var videoIsDoVi = state.VideoStream.VideoRangeType is VideoRangeType.DOVI or VideoRangeType.DOVIWithHDR10 or VideoRangeType.DOVIWithHLG or VideoRangeType.DOVIWithSDR;
+ var videoIsDoVi = EncodingHelper.IsDovi(state.VideoStream);
if (EncodingHelper.IsCopyCodec(codec)
- && (videoIsDoVi && clientSupportsDoVi))
+ && (videoIsDoVi && clientSupportsDoVi)
+ && !_encodingHelper.IsDoviRemoved(state))
{
if (isActualOutputVideoCodecHevc)
{
@@ -1855,7 +1857,7 @@ public class DynamicHlsController : BaseJellyfinApiController
// If h264_mp4toannexb is ever added, do not use it for live tv.
if (state.VideoStream is not null && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
{
- string bitStreamArgs = EncodingHelper.GetBitStreamArgs(state.VideoStream);
+ string bitStreamArgs = _encodingHelper.GetBitStreamArgs(state, MediaStreamType.Video);
if (!string.IsNullOrEmpty(bitStreamArgs))
{
args += " " + bitStreamArgs;
diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs
index e7b7405ca..abda053d3 100644
--- a/Jellyfin.Api/Controllers/ImageController.cs
+++ b/Jellyfin.Api/Controllers/ImageController.cs
@@ -1727,7 +1727,8 @@ public class ImageController : BaseJellyfinApiController
[FromQuery, Range(0, 100)] int quality = 90)
{
var brandingOptions = _serverConfigurationManager.GetConfiguration<BrandingOptions>("branding");
- if (!brandingOptions.SplashscreenEnabled)
+ var isAdmin = User.IsInRole(Constants.UserRoles.Administrator);
+ if (!brandingOptions.SplashscreenEnabled && !isAdmin)
{
return NotFound();
}
diff --git a/Jellyfin.Api/Controllers/ItemUpdateController.cs b/Jellyfin.Api/Controllers/ItemUpdateController.cs
index d49e0753e..50eeaeac6 100644
--- a/Jellyfin.Api/Controllers/ItemUpdateController.cs
+++ b/Jellyfin.Api/Controllers/ItemUpdateController.cs
@@ -299,7 +299,7 @@ public class ItemUpdateController : BaseJellyfinApiController
if (!season.LockedFields.Contains(MetadataField.Tags))
{
- season.Tags = season.Tags.Concat(addedTags).Except(removedTags).Distinct().ToArray();
+ season.Tags = season.Tags.Concat(addedTags).Except(removedTags).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
}
season.OnMetadataChanged();
@@ -316,7 +316,7 @@ public class ItemUpdateController : BaseJellyfinApiController
if (!ep.LockedFields.Contains(MetadataField.Tags))
{
- ep.Tags = ep.Tags.Concat(addedTags).Except(removedTags).Distinct().ToArray();
+ ep.Tags = ep.Tags.Concat(addedTags).Except(removedTags).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
}
ep.OnMetadataChanged();
@@ -337,7 +337,7 @@ public class ItemUpdateController : BaseJellyfinApiController
if (!ep.LockedFields.Contains(MetadataField.Tags))
{
- ep.Tags = ep.Tags.Concat(addedTags).Except(removedTags).Distinct().ToArray();
+ ep.Tags = ep.Tags.Concat(addedTags).Except(removedTags).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
}
ep.OnMetadataChanged();
@@ -357,7 +357,7 @@ public class ItemUpdateController : BaseJellyfinApiController
if (!track.LockedFields.Contains(MetadataField.Tags))
{
- track.Tags = track.Tags.Concat(addedTags).Except(removedTags).Distinct().ToArray();
+ track.Tags = track.Tags.Concat(addedTags).Except(removedTags).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
}
track.OnMetadataChanged();
diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs
index 803c2f1f7..a49128336 100644
--- a/Jellyfin.Api/Controllers/ItemsController.cs
+++ b/Jellyfin.Api/Controllers/ItemsController.cs
@@ -448,13 +448,13 @@ public class ItemsController : BaseJellyfinApiController
// Min official rating
if (!string.IsNullOrWhiteSpace(minOfficialRating))
{
- query.MinParentalRating = _localization.GetRatingLevel(minOfficialRating);
+ query.MinParentalRating = _localization.GetRatingScore(minOfficialRating);
}
// Max official rating
if (!string.IsNullOrWhiteSpace(maxOfficialRating))
{
- query.MaxParentalRating = _localization.GetRatingLevel(maxOfficialRating);
+ query.MaxParentalRating = _localization.GetRatingScore(maxOfficialRating);
}
// Artists
diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs
index 5461d12fa..10f1789ad 100644
--- a/Jellyfin.Api/Controllers/LiveTvController.cs
+++ b/Jellyfin.Api/Controllers/LiveTvController.cs
@@ -1190,7 +1190,9 @@ public class LiveTvController : BaseJellyfinApiController
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesVideoFile]
- public ActionResult GetLiveStreamFile([FromRoute, Required] string streamId, [FromRoute, Required] string container)
+ public ActionResult GetLiveStreamFile(
+ [FromRoute, Required] string streamId,
+ [FromRoute, Required] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string container)
{
var liveStreamInfo = _mediaSourceManager.GetLiveStreamInfoByUniqueId(streamId);
if (liveStreamInfo is null)
diff --git a/Jellyfin.Api/Controllers/LocalizationController.cs b/Jellyfin.Api/Controllers/LocalizationController.cs
index f65d95c41..bbce5a9e1 100644
--- a/Jellyfin.Api/Controllers/LocalizationController.cs
+++ b/Jellyfin.Api/Controllers/LocalizationController.cs
@@ -1,5 +1,4 @@
using System.Collections.Generic;
-using Jellyfin.Api.Constants;
using MediaBrowser.Common.Api;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
@@ -45,7 +44,7 @@ public class LocalizationController : BaseJellyfinApiController
/// <returns>An <see cref="OkResult"/> containing the list of countries.</returns>
[HttpGet("Countries")]
[ProducesResponseType(StatusCodes.Status200OK)]
- public ActionResult<IEnumerable<CountryInfo>> GetCountries()
+ public ActionResult<IReadOnlyList<CountryInfo>> GetCountries()
{
return Ok(_localization.GetCountries());
}
@@ -57,7 +56,7 @@ public class LocalizationController : BaseJellyfinApiController
/// <returns>An <see cref="OkResult"/> containing the list of parental ratings.</returns>
[HttpGet("ParentalRatings")]
[ProducesResponseType(StatusCodes.Status200OK)]
- public ActionResult<IEnumerable<ParentalRating>> GetParentalRatings()
+ public ActionResult<IReadOnlyList<ParentalRating>> GetParentalRatings()
{
return Ok(_localization.GetParentalRatings());
}
diff --git a/Jellyfin.Api/Controllers/MediaSegmentsController.cs b/Jellyfin.Api/Controllers/MediaSegmentsController.cs
index e30e2b54e..b8836d7cf 100644
--- a/Jellyfin.Api/Controllers/MediaSegmentsController.cs
+++ b/Jellyfin.Api/Controllers/MediaSegmentsController.cs
@@ -5,9 +5,9 @@ using System.Linq;
using System.Threading.Tasks;
using Jellyfin.Api.Extensions;
using Jellyfin.Database.Implementations.Enums;
-using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaSegments;
using MediaBrowser.Model.MediaSegments;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization;
@@ -55,7 +55,8 @@ public class MediaSegmentsController : BaseJellyfinApiController
return NotFound();
}
- var items = await _mediaSegmentManager.GetSegmentsAsync(item, includeSegmentTypes).ConfigureAwait(false);
+ var libraryOptions = _libraryManager.GetLibraryOptions(item);
+ var items = await _mediaSegmentManager.GetSegmentsAsync(item, includeSegmentTypes, libraryOptions).ConfigureAwait(false);
return Ok(new QueryResult<MediaSegmentDto>(items.ToArray()));
}
}
diff --git a/Jellyfin.Api/Controllers/PlaylistsController.cs b/Jellyfin.Api/Controllers/PlaylistsController.cs
index ec5fdab38..79c71d23a 100644
--- a/Jellyfin.Api/Controllers/PlaylistsController.cs
+++ b/Jellyfin.Api/Controllers/PlaylistsController.cs
@@ -450,22 +450,41 @@ public class PlaylistsController : BaseJellyfinApiController
{
var callingUserId = User.GetUserId();
- var playlist = _playlistManager.GetPlaylistForUser(Guid.Parse(playlistId), callingUserId);
- if (playlist is null)
+ if (!callingUserId.IsEmpty())
{
- return NotFound("Playlist not found");
+ var playlist = _playlistManager.GetPlaylistForUser(Guid.Parse(playlistId), callingUserId);
+ if (playlist is null)
+ {
+ return NotFound("Playlist not found");
+ }
+
+ var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
+ || playlist.Shares.Any(s => s.CanEdit && s.UserId.Equals(callingUserId));
+
+ if (!isPermitted)
+ {
+ return Forbid();
+ }
}
+ else
+ {
+ var isApiKey = User.GetIsApiKey();
- var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
- || playlist.Shares.Any(s => s.CanEdit && s.UserId.Equals(callingUserId));
+ if (!isApiKey)
+ {
+ return Forbid();
+ }
+ }
- if (!isPermitted)
+ try
{
- return Forbid();
+ await _playlistManager.RemoveItemFromPlaylistAsync(playlistId, entryIds).ConfigureAwait(false);
+ return NoContent();
+ }
+ catch (ArgumentException)
+ {
+ return NotFound();
}
-
- await _playlistManager.RemoveItemFromPlaylistAsync(playlistId, entryIds).ConfigureAwait(false);
- return NoContent();
}
/// <summary>
diff --git a/Jellyfin.Api/Controllers/PlaystateController.cs b/Jellyfin.Api/Controllers/PlaystateController.cs
index 1577b4594..ade0906b3 100644
--- a/Jellyfin.Api/Controllers/PlaystateController.cs
+++ b/Jellyfin.Api/Controllers/PlaystateController.cs
@@ -272,6 +272,7 @@ public class PlaystateController : BaseJellyfinApiController
/// <returns>A <see cref="NoContentResult"/>.</returns>
[HttpPost("PlayingItems/{itemId}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Obsolete("This endpoint is obsolete. Use ReportPlaybackStart instead")]
public async Task<ActionResult> OnPlaybackStart(
[FromRoute, Required] Guid itemId,
[FromQuery] string? mediaSourceId,
@@ -350,6 +351,7 @@ public class PlaystateController : BaseJellyfinApiController
/// <returns>A <see cref="NoContentResult"/>.</returns>
[HttpPost("PlayingItems/{itemId}/Progress")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Obsolete("This endpoint is obsolete. Use ReportPlaybackProgress instead")]
public async Task<ActionResult> OnPlaybackProgress(
[FromRoute, Required] Guid itemId,
[FromQuery] string? mediaSourceId,
@@ -438,6 +440,7 @@ public class PlaystateController : BaseJellyfinApiController
/// <returns>A <see cref="NoContentResult"/>.</returns>
[HttpDelete("PlayingItems/{itemId}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Obsolete("This endpoint is obsolete. Use ReportPlaybackStop instead")]
public async Task<ActionResult> OnPlaybackStopped(
[FromRoute, Required] Guid itemId,
[FromQuery] string? mediaSourceId,
diff --git a/Jellyfin.Api/Controllers/StartupController.cs b/Jellyfin.Api/Controllers/StartupController.cs
index a6bc84311..09f20558f 100644
--- a/Jellyfin.Api/Controllers/StartupController.cs
+++ b/Jellyfin.Api/Controllers/StartupController.cs
@@ -58,6 +58,7 @@ public class StartupController : BaseJellyfinApiController
{
return new StartupConfigurationDto
{
+ ServerName = _config.Configuration.ServerName,
UICulture = _config.Configuration.UICulture,
MetadataCountryCode = _config.Configuration.MetadataCountryCode,
PreferredMetadataLanguage = _config.Configuration.PreferredMetadataLanguage
@@ -74,6 +75,7 @@ public class StartupController : BaseJellyfinApiController
[ProducesResponseType(StatusCodes.Status204NoContent)]
public ActionResult UpdateInitialConfiguration([FromBody, Required] StartupConfigurationDto startupConfiguration)
{
+ _config.Configuration.ServerName = startupConfiguration.ServerName ?? string.Empty;
_config.Configuration.UICulture = startupConfiguration.UICulture ?? string.Empty;
_config.Configuration.MetadataCountryCode = startupConfiguration.MetadataCountryCode ?? string.Empty;
_config.Configuration.PreferredMetadataLanguage = startupConfiguration.PreferredMetadataLanguage ?? string.Empty;
@@ -112,8 +114,7 @@ public class StartupController : BaseJellyfinApiController
var user = _userManager.Users.First();
return new StartupUserDto
{
- Name = user.Username,
- Password = user.Password
+ Name = user.Username
};
}
diff --git a/Jellyfin.Api/Controllers/SyncPlayController.cs b/Jellyfin.Api/Controllers/SyncPlayController.cs
index 383978197..3d6874079 100644
--- a/Jellyfin.Api/Controllers/SyncPlayController.cs
+++ b/Jellyfin.Api/Controllers/SyncPlayController.cs
@@ -1,9 +1,9 @@
+using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using Jellyfin.Api.Constants;
using Jellyfin.Api.Helpers;
using Jellyfin.Api.Models.SyncPlayDtos;
using MediaBrowser.Common.Api;
@@ -50,17 +50,16 @@ public class SyncPlayController : BaseJellyfinApiController
/// </summary>
/// <param name="requestData">The settings of the new group.</param>
/// <response code="204">New group created.</response>
- /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ /// <returns>An <see cref="GroupInfoDto"/> for the created group.</returns>
[HttpPost("New")]
- [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
[Authorize(Policy = Policies.SyncPlayCreateGroup)]
- public async Task<ActionResult> SyncPlayCreateGroup(
+ public async Task<ActionResult<GroupInfoDto>> SyncPlayCreateGroup(
[FromBody, Required] NewGroupRequestDto requestData)
{
var currentSession = await RequestHelpers.GetSession(_sessionManager, _userManager, HttpContext).ConfigureAwait(false);
var syncPlayRequest = new NewGroupRequest(requestData.GroupName);
- _syncPlayManager.NewGroup(currentSession, syncPlayRequest, CancellationToken.None);
- return NoContent();
+ return Ok(_syncPlayManager.NewGroup(currentSession, syncPlayRequest, CancellationToken.None));
}
/// <summary>
@@ -113,6 +112,23 @@ public class SyncPlayController : BaseJellyfinApiController
}
/// <summary>
+ /// Gets a SyncPlay group by id.
+ /// </summary>
+ /// <param name="id">The id of the group.</param>
+ /// <response code="200">Group returned.</response>
+ /// <returns>An <see cref="GroupInfoDto"/> for the requested group.</returns>
+ [HttpGet("{id:guid}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [Authorize(Policy = Policies.SyncPlayJoinGroup)]
+ public async Task<ActionResult<GroupInfoDto>> SyncPlayGetGroup([FromRoute] Guid id)
+ {
+ var currentSession = await RequestHelpers.GetSession(_sessionManager, _userManager, HttpContext).ConfigureAwait(false);
+ var group = _syncPlayManager.GetGroup(currentSession, id);
+ return group is null ? NotFound() : Ok(group);
+ }
+
+ /// <summary>
/// Request to set new playlist in SyncPlay group.
/// </summary>
/// <param name="requestData">The new playlist to play in the group.</param>
diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs
index 0ee11c070..450225c37 100644
--- a/Jellyfin.Api/Controllers/SystemController.cs
+++ b/Jellyfin.Api/Controllers/SystemController.cs
@@ -5,7 +5,7 @@ using System.IO;
using System.Linq;
using System.Net.Mime;
using Jellyfin.Api.Attributes;
-using Jellyfin.Api.Constants;
+using Jellyfin.Api.Models.SystemInfoDtos;
using MediaBrowser.Common.Api;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
@@ -72,6 +72,19 @@ public class SystemController : BaseJellyfinApiController
=> _systemManager.GetSystemInfo(Request);
/// <summary>
+ /// Gets information about the server.
+ /// </summary>
+ /// <response code="200">Information retrieved.</response>
+ /// <response code="403">User does not have permission to retrieve information.</response>
+ /// <returns>A <see cref="SystemInfo"/> with info about the system.</returns>
+ [HttpGet("Info/Storage")]
+ [Authorize(Policy = Policies.RequiresElevation)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ public ActionResult<SystemStorageDto> GetSystemStorage()
+ => Ok(SystemStorageDto.FromSystemStorageInfo(_systemManager.GetSystemStorageInfo()));
+
+ /// <summary>
/// Gets public information about the server.
/// </summary>
/// <response code="200">Information retrieved.</response>
diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs
index a5b5fde62..fd6334703 100644
--- a/Jellyfin.Api/Controllers/UniversalAudioController.cs
+++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs
@@ -102,13 +102,13 @@ public class UniversalAudioController : BaseJellyfinApiController
[FromQuery] string? mediaSourceId,
[FromQuery] string? deviceId,
[FromQuery] Guid? userId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
[FromQuery] int? maxAudioChannels,
[FromQuery] int? transcodingAudioChannels,
[FromQuery] int? maxStreamingBitrate,
[FromQuery] int? audioBitRate,
[FromQuery] long? startTimeTicks,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? transcodingContainer,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? transcodingContainer,
[FromQuery] MediaStreamProtocol? transcodingProtocol,
[FromQuery] int? maxAudioSampleRate,
[FromQuery] int? maxAudioBitDepth,
diff --git a/Jellyfin.Api/Controllers/VideosController.cs b/Jellyfin.Api/Controllers/VideosController.cs
index 6f18c1603..97f3239bb 100644
--- a/Jellyfin.Api/Controllers/VideosController.cs
+++ b/Jellyfin.Api/Controllers/VideosController.cs
@@ -315,18 +315,18 @@ public class VideosController : BaseJellyfinApiController
[ProducesVideoFile]
public async Task<ActionResult> GetVideoStream(
[FromRoute, Required] Guid itemId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? container,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? container,
[FromQuery] bool? @static,
[FromQuery] string? @params,
[FromQuery] string? tag,
[FromQuery, ParameterObsolete] string? deviceProfileId,
[FromQuery] string? playSessionId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? segmentContainer,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
[FromQuery] int? segmentLength,
[FromQuery] int? minSegments,
[FromQuery] string? mediaSourceId,
[FromQuery] string? deviceId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
[FromQuery] bool? enableAutoStreamCopy,
[FromQuery] bool? allowVideoStreamCopy,
[FromQuery] bool? allowAudioStreamCopy,
@@ -337,7 +337,7 @@ public class VideosController : BaseJellyfinApiController
[FromQuery] int? audioChannels,
[FromQuery] int? maxAudioChannels,
[FromQuery] string? profile,
- [FromQuery] string? level,
+ [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
[FromQuery] float? framerate,
[FromQuery] float? maxFramerate,
[FromQuery] bool? copyTimestamps,
@@ -358,8 +358,8 @@ public class VideosController : BaseJellyfinApiController
[FromQuery] int? cpuCoreLimit,
[FromQuery] string? liveStreamId,
[FromQuery] bool? enableMpegtsM2TsMode,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? videoCodec,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? subtitleCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
[FromQuery] string? transcodeReasons,
[FromQuery] int? audioStreamIndex,
[FromQuery] int? videoStreamIndex,
@@ -556,18 +556,18 @@ public class VideosController : BaseJellyfinApiController
[ProducesVideoFile]
public Task<ActionResult> GetVideoStreamByContainer(
[FromRoute, Required] Guid itemId,
- [FromRoute, Required] string container,
+ [FromRoute, Required] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string container,
[FromQuery] bool? @static,
[FromQuery] string? @params,
[FromQuery] string? tag,
[FromQuery] string? deviceProfileId,
[FromQuery] string? playSessionId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? segmentContainer,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
[FromQuery] int? segmentLength,
[FromQuery] int? minSegments,
[FromQuery] string? mediaSourceId,
[FromQuery] string? deviceId,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
[FromQuery] bool? enableAutoStreamCopy,
[FromQuery] bool? allowVideoStreamCopy,
[FromQuery] bool? allowAudioStreamCopy,
@@ -578,7 +578,7 @@ public class VideosController : BaseJellyfinApiController
[FromQuery] int? audioChannels,
[FromQuery] int? maxAudioChannels,
[FromQuery] string? profile,
- [FromQuery] string? level,
+ [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
[FromQuery] float? framerate,
[FromQuery] float? maxFramerate,
[FromQuery] bool? copyTimestamps,
@@ -599,8 +599,8 @@ public class VideosController : BaseJellyfinApiController
[FromQuery] int? cpuCoreLimit,
[FromQuery] string? liveStreamId,
[FromQuery] bool? enableMpegtsM2TsMode,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? videoCodec,
- [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? subtitleCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
+ [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
[FromQuery] string? transcodeReasons,
[FromQuery] int? audioStreamIndex,
[FromQuery] int? videoStreamIndex,
diff --git a/Jellyfin.Api/Controllers/YearsController.cs b/Jellyfin.Api/Controllers/YearsController.cs
index ebf98da45..b60258586 100644
--- a/Jellyfin.Api/Controllers/YearsController.cs
+++ b/Jellyfin.Api/Controllers/YearsController.cs
@@ -223,6 +223,6 @@ public class YearsController : BaseJellyfinApiController
.Select(i => i.ProductionYear ?? 0)
.Where(i => i > 0)
.Distinct()
- .Select(year => _libraryManager.GetYear(year));
+ .Select(_libraryManager.GetYear);
}
}
diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs
index ebd0288ca..a38ad379c 100644
--- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs
+++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs
@@ -345,13 +345,15 @@ public class DynamicHlsHelper
if (videoRange == VideoRange.HDR)
{
- if (videoRangeType == VideoRangeType.HLG)
+ switch (videoRangeType)
{
- builder.Append(",VIDEO-RANGE=HLG");
- }
- else
- {
- builder.Append(",VIDEO-RANGE=PQ");
+ case VideoRangeType.HLG:
+ case VideoRangeType.DOVIWithHLG:
+ builder.Append(",VIDEO-RANGE=HLG");
+ break;
+ default:
+ builder.Append(",VIDEO-RANGE=PQ");
+ break;
}
}
}
@@ -418,36 +420,67 @@ public class DynamicHlsHelper
/// <param name="state">StreamState of the current stream.</param>
private void AppendPlaylistSupplementalCodecsField(StringBuilder builder, StreamState state)
{
- // Dolby Vision currently cannot exist when transcoding
+ // HDR dynamic metadata currently cannot exist when transcoding
if (!EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
{
return;
}
- var dvProfile = state.VideoStream.DvProfile;
- var dvLevel = state.VideoStream.DvLevel;
- var dvRangeString = state.VideoStream.VideoRangeType switch
+ if (EncodingHelper.IsDovi(state.VideoStream) && !_encodingHelper.IsDoviRemoved(state))
{
- VideoRangeType.DOVIWithHDR10 => "db1p",
- VideoRangeType.DOVIWithHLG => "db4h",
- _ => string.Empty
- };
+ AppendDvString();
+ }
+ else if (EncodingHelper.IsHdr10Plus(state.VideoStream) && !_encodingHelper.IsHdr10PlusRemoved(state))
+ {
+ AppendHdr10PlusString();
+ }
- if (dvProfile is null || dvLevel is null || string.IsNullOrEmpty(dvRangeString))
+ return;
+
+ void AppendDvString()
{
- return;
+ var dvProfile = state.VideoStream.DvProfile;
+ var dvLevel = state.VideoStream.DvLevel;
+ var dvRangeString = state.VideoStream.VideoRangeType switch
+ {
+ VideoRangeType.DOVIWithHDR10 => "db1p",
+ VideoRangeType.DOVIWithHLG => "db4h",
+ VideoRangeType.DOVIWithHDR10Plus => "db1p", // The HDR10+ metadata would be removed if Dovi metadata is not removed
+ _ => string.Empty // Don't label Dovi with EL and SDR due to compatability issues, ignore invalid configurations
+ };
+
+ if (dvProfile is null || dvLevel is null || string.IsNullOrEmpty(dvRangeString))
+ {
+ return;
+ }
+
+ var dvFourCc = string.Equals(state.ActualOutputVideoCodec, "av1", StringComparison.OrdinalIgnoreCase) ? "dav1" : "dvh1";
+ builder.Append(",SUPPLEMENTAL-CODECS=\"")
+ .Append(dvFourCc)
+ .Append('.')
+ .Append(dvProfile.Value.ToString("D2", CultureInfo.InvariantCulture))
+ .Append('.')
+ .Append(dvLevel.Value.ToString("D2", CultureInfo.InvariantCulture))
+ .Append('/')
+ .Append(dvRangeString)
+ .Append('"');
}
- var dvFourCc = string.Equals(state.ActualOutputVideoCodec, "av1", StringComparison.OrdinalIgnoreCase) ? "dav1" : "dvh1";
- builder.Append(",SUPPLEMENTAL-CODECS=\"")
- .Append(dvFourCc)
- .Append('.')
- .Append(dvProfile.Value.ToString("D2", CultureInfo.InvariantCulture))
- .Append('.')
- .Append(dvLevel.Value.ToString("D2", CultureInfo.InvariantCulture))
- .Append('/')
- .Append(dvRangeString)
- .Append('"');
+ void AppendHdr10PlusString()
+ {
+ var videoCodecLevel = GetOutputVideoCodecLevel(state);
+ if (string.IsNullOrEmpty(state.ActualOutputVideoCodec) || videoCodecLevel is null)
+ {
+ return;
+ }
+
+ var videoCodecString = GetPlaylistVideoCodecs(state, state.ActualOutputVideoCodec, videoCodecLevel.Value);
+ builder.Append(",SUPPLEMENTAL-CODECS=\"")
+ .Append(videoCodecString)
+ .Append('/')
+ .Append("cdm4")
+ .Append('"');
+ }
}
/// <summary>
diff --git a/Jellyfin.Api/Helpers/MediaInfoHelper.cs b/Jellyfin.Api/Helpers/MediaInfoHelper.cs
index 63c9c173b..454d3f08e 100644
--- a/Jellyfin.Api/Helpers/MediaInfoHelper.cs
+++ b/Jellyfin.Api/Helpers/MediaInfoHelper.cs
@@ -129,6 +129,13 @@ public class MediaInfoHelper
var mediaSourcesClone = JsonSerializer.Deserialize<MediaSourceInfo[]>(JsonSerializer.SerializeToUtf8Bytes(mediaSources));
if (mediaSourcesClone is not null)
{
+ // Carry over the default audio index source.
+ // This field is not intended to be exposed to API clients, but it is used internally by the server
+ for (int i = 0; i < mediaSourcesClone.Length && i < mediaSources.Length; i++)
+ {
+ mediaSourcesClone[i].DefaultAudioIndexSource = mediaSources[i].DefaultAudioIndexSource;
+ }
+
result.MediaSources = mediaSourcesClone;
}
diff --git a/Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs b/Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs
index 842a69dd9..a0ed6c812 100644
--- a/Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs
+++ b/Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs
@@ -1,8 +1,10 @@
using System.Net;
using System.Threading.Tasks;
+using System.Web;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Logging;
namespace Jellyfin.Api.Middleware;
@@ -12,14 +14,17 @@ namespace Jellyfin.Api.Middleware;
public class IPBasedAccessValidationMiddleware
{
private readonly RequestDelegate _next;
+ private readonly ILogger<IPBasedAccessValidationMiddleware> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="IPBasedAccessValidationMiddleware"/> class.
/// </summary>
/// <param name="next">The next delegate in the pipeline.</param>
- public IPBasedAccessValidationMiddleware(RequestDelegate next)
+ /// <param name="logger">The logger to log to.</param>
+ public IPBasedAccessValidationMiddleware(RequestDelegate next, ILogger<IPBasedAccessValidationMiddleware> logger)
{
_next = next;
+ _logger = logger;
}
/// <summary>
@@ -32,16 +37,23 @@ public class IPBasedAccessValidationMiddleware
{
if (httpContext.IsLocal())
{
- // Running locally.
+ // Accessing from the same machine as the server.
await _next(httpContext).ConfigureAwait(false);
return;
}
- var remoteIP = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback;
+ var remoteIP = httpContext.GetNormalizedRemoteIP();
- if (!networkManager.HasRemoteAccess(remoteIP))
+ var result = networkManager.ShouldAllowServerAccess(remoteIP);
+ if (result != RemoteAccessPolicyResult.Allow)
{
// No access from network, respond with 503 instead of 200.
+ _logger.LogWarning(
+ "Blocking request to {Path} by {RemoteIP} due to IP filtering rule, reason: {Reason}",
+ // url-encode to block log injection
+ HttpUtility.UrlEncode(httpContext.Request.Path),
+ remoteIP,
+ result);
httpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
return;
}
diff --git a/Jellyfin.Api/Middleware/LanFilteringMiddleware.cs b/Jellyfin.Api/Middleware/LanFilteringMiddleware.cs
deleted file mode 100644
index 35b0a1dd0..000000000
--- a/Jellyfin.Api/Middleware/LanFilteringMiddleware.cs
+++ /dev/null
@@ -1,51 +0,0 @@
-using System.Net;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using Microsoft.AspNetCore.Http;
-
-namespace Jellyfin.Api.Middleware;
-
-/// <summary>
-/// Validates the LAN host IP based on application configuration.
-/// </summary>
-public class LanFilteringMiddleware
-{
- private readonly RequestDelegate _next;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="LanFilteringMiddleware"/> class.
- /// </summary>
- /// <param name="next">The next delegate in the pipeline.</param>
- public LanFilteringMiddleware(RequestDelegate next)
- {
- _next = next;
- }
-
- /// <summary>
- /// Executes the middleware action.
- /// </summary>
- /// <param name="httpContext">The current HTTP context.</param>
- /// <param name="networkManager">The network manager.</param>
- /// <param name="serverConfigurationManager">The server configuration manager.</param>
- /// <returns>The async task.</returns>
- public async Task Invoke(HttpContext httpContext, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager)
- {
- if (serverConfigurationManager.GetNetworkConfiguration().EnableRemoteAccess)
- {
- await _next(httpContext).ConfigureAwait(false);
- return;
- }
-
- var host = httpContext.GetNormalizedRemoteIP();
- if (!networkManager.IsInLocalNetwork(host))
- {
- // No access from network, respond with 503 instead of 200.
- httpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
- return;
- }
-
- await _next(httpContext).ConfigureAwait(false);
- }
-}
diff --git a/Jellyfin.Api/Models/StartupDtos/StartupConfigurationDto.cs b/Jellyfin.Api/Models/StartupDtos/StartupConfigurationDto.cs
index 402707819..1ba23339d 100644
--- a/Jellyfin.Api/Models/StartupDtos/StartupConfigurationDto.cs
+++ b/Jellyfin.Api/Models/StartupDtos/StartupConfigurationDto.cs
@@ -6,6 +6,11 @@ namespace Jellyfin.Api.Models.StartupDtos;
public class StartupConfigurationDto
{
/// <summary>
+ /// Gets or sets the server name.
+ /// </summary>
+ public string? ServerName { get; set; }
+
+ /// <summary>
/// Gets or sets UI language culture.
/// </summary>
public string? UICulture { get; set; }
diff --git a/Jellyfin.Api/Models/SystemInfoDtos/FolderStorageDto.cs b/Jellyfin.Api/Models/SystemInfoDtos/FolderStorageDto.cs
new file mode 100644
index 000000000..00a965898
--- /dev/null
+++ b/Jellyfin.Api/Models/SystemInfoDtos/FolderStorageDto.cs
@@ -0,0 +1,46 @@
+using MediaBrowser.Model.System;
+
+namespace Jellyfin.Api.Models.SystemInfoDtos;
+
+/// <summary>
+/// Contains information about a specific folder.
+/// </summary>
+public record FolderStorageDto
+{
+ /// <summary>
+ /// Gets the path of the folder in question.
+ /// </summary>
+ public required string Path { get; init; }
+
+ /// <summary>
+ /// Gets the free space of the underlying storage device of the <see cref="Path"/>.
+ /// </summary>
+ public long FreeSpace { get; init; }
+
+ /// <summary>
+ /// Gets the used space of the underlying storage device of the <see cref="Path"/>.
+ /// </summary>
+ public long UsedSpace { get; init; }
+
+ /// <summary>
+ /// Gets the kind of storage device of the <see cref="Path"/>.
+ /// </summary>
+ public string? StorageType { get; init; }
+
+ /// <summary>
+ /// Gets the Device Identifier.
+ /// </summary>
+ public string? DeviceId { get; init; }
+
+ internal static FolderStorageDto FromFolderStorageInfo(FolderStorageInfo model)
+ {
+ return new()
+ {
+ Path = model.Path,
+ FreeSpace = model.FreeSpace,
+ UsedSpace = model.UsedSpace,
+ StorageType = model.StorageType,
+ DeviceId = model.DeviceId
+ };
+ }
+}
diff --git a/Jellyfin.Api/Models/SystemInfoDtos/LibraryStorageDto.cs b/Jellyfin.Api/Models/SystemInfoDtos/LibraryStorageDto.cs
new file mode 100644
index 000000000..c138324d2
--- /dev/null
+++ b/Jellyfin.Api/Models/SystemInfoDtos/LibraryStorageDto.cs
@@ -0,0 +1,37 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using MediaBrowser.Model.System;
+
+namespace Jellyfin.Api.Models.SystemInfoDtos;
+
+/// <summary>
+/// Contains informations about a libraries storage informations.
+/// </summary>
+public record LibraryStorageDto
+{
+ /// <summary>
+ /// Gets or sets the Library Id.
+ /// </summary>
+ public required Guid Id { get; set; }
+
+ /// <summary>
+ /// Gets or sets the name of the library.
+ /// </summary>
+ public required string Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the storage informations about the folders used in a library.
+ /// </summary>
+ public required IReadOnlyCollection<FolderStorageDto> Folders { get; set; }
+
+ internal static LibraryStorageDto FromLibraryStorageModel(LibraryStorageInfo model)
+ {
+ return new()
+ {
+ Id = model.Id,
+ Name = model.Name,
+ Folders = model.Folders.Select(FolderStorageDto.FromFolderStorageInfo).ToArray()
+ };
+ }
+}
diff --git a/Jellyfin.Api/Models/SystemInfoDtos/SystemStorageDto.cs b/Jellyfin.Api/Models/SystemInfoDtos/SystemStorageDto.cs
new file mode 100644
index 000000000..a09042439
--- /dev/null
+++ b/Jellyfin.Api/Models/SystemInfoDtos/SystemStorageDto.cs
@@ -0,0 +1,67 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using MediaBrowser.Model.System;
+
+namespace Jellyfin.Api.Models.SystemInfoDtos;
+
+/// <summary>
+/// Contains informations about the systems storage.
+/// </summary>
+public record SystemStorageDto
+{
+ /// <summary>
+ /// Gets or sets the Storage information of the program data folder.
+ /// </summary>
+ public required FolderStorageDto ProgramDataFolder { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Storage information of the web UI resources folder.
+ /// </summary>
+ public required FolderStorageDto WebFolder { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Storage information of the folder where images are cached.
+ /// </summary>
+ public required FolderStorageDto ImageCacheFolder { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Storage information of the cache folder.
+ /// </summary>
+ public required FolderStorageDto CacheFolder { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Storage information of the folder where logfiles are saved to.
+ /// </summary>
+ public required FolderStorageDto LogFolder { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Storage information of the folder where metadata is stored.
+ /// </summary>
+ public required FolderStorageDto InternalMetadataFolder { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Storage information of the transcoding cache.
+ /// </summary>
+ public required FolderStorageDto TranscodingTempFolder { get; set; }
+
+ /// <summary>
+ /// Gets or sets the storage informations of all libraries.
+ /// </summary>
+ public required IReadOnlyCollection<LibraryStorageDto> Libraries { get; set; }
+
+ internal static SystemStorageDto FromSystemStorageInfo(SystemStorageInfo model)
+ {
+ return new SystemStorageDto()
+ {
+ ProgramDataFolder = FolderStorageDto.FromFolderStorageInfo(model.ProgramDataFolder),
+ WebFolder = FolderStorageDto.FromFolderStorageInfo(model.WebFolder),
+ ImageCacheFolder = FolderStorageDto.FromFolderStorageInfo(model.ImageCacheFolder),
+ CacheFolder = FolderStorageDto.FromFolderStorageInfo(model.CacheFolder),
+ LogFolder = FolderStorageDto.FromFolderStorageInfo(model.LogFolder),
+ InternalMetadataFolder = FolderStorageDto.FromFolderStorageInfo(model.InternalMetadataFolder),
+ TranscodingTempFolder = FolderStorageDto.FromFolderStorageInfo(model.TranscodingTempFolder),
+ Libraries = model.Libraries.Select(LibraryStorageDto.FromLibraryStorageModel).ToArray()
+ };
+ }
+}
diff --git a/Jellyfin.Data/Enums/VideoRangeType.cs b/Jellyfin.Data/Enums/VideoRangeType.cs
index 853c2c73d..ce232d73c 100644
--- a/Jellyfin.Data/Enums/VideoRangeType.cs
+++ b/Jellyfin.Data/Enums/VideoRangeType.cs
@@ -46,6 +46,27 @@ public enum VideoRangeType
DOVIWithSDR,
/// <summary>
+ /// Dolby Vision with Enhancment Layer (Profile 7).
+ /// </summary>
+ DOVIWithEL,
+
+ /// <summary>
+ /// Dolby Vision and HDR10+ Metadata coexists.
+ /// </summary>
+ DOVIWithHDR10Plus,
+
+ /// <summary>
+ /// Dolby Vision with Enhancment Layer (Profile 7) and HDR10+ Metadata coexists.
+ /// </summary>
+ DOVIWithELHDR10Plus,
+
+ /// <summary>
+ /// Dolby Vision with invalid configuration. e.g. Profile 8 compat id 6.
+ /// When using this range, the server would assume the video is still HDR10 after removing the Dolby Vision metadata.
+ /// </summary>
+ DOVIInvalid,
+
+ /// <summary>
/// HDR10+ video range type (10bit to 16bit).
/// </summary>
HDR10Plus
diff --git a/Jellyfin.Server.Implementations/Extensions/ExpressionExtensions.cs b/Jellyfin.Server.Implementations/Extensions/ExpressionExtensions.cs
new file mode 100644
index 000000000..d70ac672f
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Extensions/ExpressionExtensions.cs
@@ -0,0 +1,70 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Linq.Expressions;
+
+namespace Jellyfin.Server.Implementations.Extensions;
+
+/// <summary>
+/// Provides <see cref="Expression"/> extension methods.
+/// </summary>
+public static class ExpressionExtensions
+{
+ /// <summary>
+ /// Combines two predicates into a single predicate using a logical OR operation.
+ /// </summary>
+ /// <typeparam name="T">The predicate parameter type.</typeparam>
+ /// <param name="firstPredicate">The first predicate expression to combine.</param>
+ /// <param name="secondPredicate">The second predicate expression to combine.</param>
+ /// <returns>A new expression representing the OR combination of the input predicates.</returns>
+ public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> firstPredicate, Expression<Func<T, bool>> secondPredicate)
+ {
+ ArgumentNullException.ThrowIfNull(firstPredicate);
+ ArgumentNullException.ThrowIfNull(secondPredicate);
+
+ var invokedExpression = Expression.Invoke(secondPredicate, firstPredicate.Parameters);
+ return Expression.Lambda<Func<T, bool>>(Expression.OrElse(firstPredicate.Body, invokedExpression), firstPredicate.Parameters);
+ }
+
+ /// <summary>
+ /// Combines multiple predicates into a single predicate using a logical OR operation.
+ /// </summary>
+ /// <typeparam name="T">The predicate parameter type.</typeparam>
+ /// <param name="predicates">A collection of predicate expressions to combine.</param>
+ /// <returns>A new expression representing the OR combination of all input predicates.</returns>
+ public static Expression<Func<T, bool>> Or<T>(this IEnumerable<Expression<Func<T, bool>>> predicates)
+ {
+ ArgumentNullException.ThrowIfNull(predicates);
+
+ return predicates.Aggregate((aggregatePredicate, nextPredicate) => aggregatePredicate.Or(nextPredicate));
+ }
+
+ /// <summary>
+ /// Combines two predicates into a single predicate using a logical AND operation.
+ /// </summary>
+ /// <typeparam name="T">The predicate parameter type.</typeparam>
+ /// <param name="firstPredicate">The first predicate expression to combine.</param>
+ /// <param name="secondPredicate">The second predicate expression to combine.</param>
+ /// <returns>A new expression representing the AND combination of the input predicates.</returns>
+ public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> firstPredicate, Expression<Func<T, bool>> secondPredicate)
+ {
+ ArgumentNullException.ThrowIfNull(firstPredicate);
+ ArgumentNullException.ThrowIfNull(secondPredicate);
+
+ var invokedExpression = Expression.Invoke(secondPredicate, firstPredicate.Parameters);
+ return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(firstPredicate.Body, invokedExpression), firstPredicate.Parameters);
+ }
+
+ /// <summary>
+ /// Combines multiple predicates into a single predicate using a logical AND operation.
+ /// </summary>
+ /// <typeparam name="T">The predicate parameter type.</typeparam>
+ /// <param name="predicates">A collection of predicate expressions to combine.</param>
+ /// <returns>A new expression representing the AND combination of all input predicates.</returns>
+ public static Expression<Func<T, bool>> And<T>(this IEnumerable<Expression<Func<T, bool>>> predicates)
+ {
+ ArgumentNullException.ThrowIfNull(predicates);
+
+ return predicates.Aggregate((aggregatePredicate, nextPredicate) => aggregatePredicate.And(nextPredicate));
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Extensions/ServiceCollectionExtensions.cs b/Jellyfin.Server.Implementations/Extensions/ServiceCollectionExtensions.cs
index fbbb5bca7..63c80634f 100644
--- a/Jellyfin.Server.Implementations/Extensions/ServiceCollectionExtensions.cs
+++ b/Jellyfin.Server.Implementations/Extensions/ServiceCollectionExtensions.cs
@@ -1,8 +1,11 @@
using System;
using System.Collections.Generic;
+using System.IO;
+using System.Linq;
using System.Reflection;
using Jellyfin.Database.Implementations;
using Jellyfin.Database.Implementations.DbConfiguration;
+using Jellyfin.Database.Implementations.Locking;
using Jellyfin.Database.Providers.Sqlite;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Configuration;
@@ -41,6 +44,28 @@ public static class ServiceCollectionExtensions
return items;
}
+ private static JellyfinDbProviderFactory? LoadDatabasePlugin(CustomDatabaseOptions customProviderOptions, IApplicationPaths applicationPaths)
+ {
+ var plugin = Directory.EnumerateDirectories(applicationPaths.PluginsPath)
+ .Where(e => Path.GetFileName(e)!.StartsWith(customProviderOptions.PluginName, StringComparison.OrdinalIgnoreCase))
+ .Order()
+ .FirstOrDefault()
+ ?? throw new InvalidOperationException($"The requested custom database plugin with the name '{customProviderOptions.PluginName}' could not been found in '{applicationPaths.PluginsPath}'");
+
+ var dbProviderAssembly = Path.Combine(plugin, Path.ChangeExtension(customProviderOptions.PluginAssembly, "dll"));
+ if (!File.Exists(dbProviderAssembly))
+ {
+ throw new InvalidOperationException($"Could not find the requested assembly at '{dbProviderAssembly}'");
+ }
+
+ // we have to load the assembly without proxy to ensure maximum performance for this.
+ var assembly = Assembly.LoadFrom(dbProviderAssembly);
+ var dbProviderType = assembly.GetExportedTypes().FirstOrDefault(f => f.IsAssignableTo(typeof(IJellyfinDatabaseProvider)))
+ ?? throw new InvalidOperationException($"Could not find any type implementing the '{nameof(IJellyfinDatabaseProvider)}' interface.");
+
+ return (services) => (IJellyfinDatabaseProvider)ActivatorUtilities.CreateInstance(services, dbProviderType);
+ }
+
/// <summary>
/// Adds the <see cref="IDbContextFactory{TContext}"/> interface to the service collection with second level caching enabled.
/// </summary>
@@ -54,7 +79,6 @@ public static class ServiceCollectionExtensions
IConfiguration configuration)
{
var efCoreConfiguration = configurationManager.GetConfiguration<DatabaseConfigurationOptions>("database");
- var providers = GetSupportedDbProviders();
JellyfinDbProviderFactory? providerFactory = null;
if (efCoreConfiguration?.DatabaseType is null)
@@ -73,22 +97,51 @@ public static class ServiceCollectionExtensions
efCoreConfiguration = new DatabaseConfigurationOptions()
{
DatabaseType = "Jellyfin-SQLite",
+ LockingBehavior = DatabaseLockingBehaviorTypes.NoLock
};
configurationManager.SaveConfiguration("database", efCoreConfiguration);
}
}
- if (!providers.TryGetValue(efCoreConfiguration.DatabaseType.ToUpperInvariant(), out providerFactory!))
+ if (efCoreConfiguration.DatabaseType.Equals("PLUGIN_PROVIDER", StringComparison.OrdinalIgnoreCase))
+ {
+ if (efCoreConfiguration.CustomProviderOptions is null)
+ {
+ throw new InvalidOperationException("The custom database provider must declare the custom provider options to work");
+ }
+
+ providerFactory = LoadDatabasePlugin(efCoreConfiguration.CustomProviderOptions, configurationManager.ApplicationPaths);
+ }
+ else
{
- throw new InvalidOperationException($"Jellyfin cannot find the database provider of type '{efCoreConfiguration.DatabaseType}'. Supported types are {string.Join(", ", providers.Keys)}");
+ var providers = GetSupportedDbProviders();
+ if (!providers.TryGetValue(efCoreConfiguration.DatabaseType.ToUpperInvariant(), out providerFactory!))
+ {
+ throw new InvalidOperationException($"Jellyfin cannot find the database provider of type '{efCoreConfiguration.DatabaseType}'. Supported types are {string.Join(", ", providers.Keys)}");
+ }
}
serviceCollection.AddSingleton<IJellyfinDatabaseProvider>(providerFactory!);
+ switch (efCoreConfiguration.LockingBehavior)
+ {
+ case DatabaseLockingBehaviorTypes.NoLock:
+ serviceCollection.AddSingleton<IEntityFrameworkCoreLockingBehavior, NoLockBehavior>();
+ break;
+ case DatabaseLockingBehaviorTypes.Pessimistic:
+ serviceCollection.AddSingleton<IEntityFrameworkCoreLockingBehavior, PessimisticLockBehavior>();
+ break;
+ case DatabaseLockingBehaviorTypes.Optimistic:
+ serviceCollection.AddSingleton<IEntityFrameworkCoreLockingBehavior, OptimisticLockBehavior>();
+ break;
+ }
+
serviceCollection.AddPooledDbContextFactory<JellyfinDbContext>((serviceProvider, opt) =>
{
var provider = serviceProvider.GetRequiredService<IJellyfinDatabaseProvider>();
provider.Initialise(opt);
+ var lockingBehavior = serviceProvider.GetRequiredService<IEntityFrameworkCoreLockingBehavior>();
+ lockingBehavior.Initialise(opt);
});
return serviceCollection;
diff --git a/Jellyfin.Server.Implementations/FullSystemBackup/BackupManifest.cs b/Jellyfin.Server.Implementations/FullSystemBackup/BackupManifest.cs
new file mode 100644
index 000000000..77a49b2b5
--- /dev/null
+++ b/Jellyfin.Server.Implementations/FullSystemBackup/BackupManifest.cs
@@ -0,0 +1,19 @@
+using System;
+
+namespace Jellyfin.Server.Implementations.FullSystemBackup;
+
+/// <summary>
+/// Manifest type for backups internal structure.
+/// </summary>
+internal class BackupManifest
+{
+ public required Version ServerVersion { get; set; }
+
+ public required Version BackupEngineVersion { get; set; }
+
+ public required DateTimeOffset DateCreated { get; set; }
+
+ public required string[] DatabaseTables { get; set; }
+
+ public required BackupOptions Options { get; set; }
+}
diff --git a/Jellyfin.Server.Implementations/FullSystemBackup/BackupOptions.cs b/Jellyfin.Server.Implementations/FullSystemBackup/BackupOptions.cs
new file mode 100644
index 000000000..8bd108c44
--- /dev/null
+++ b/Jellyfin.Server.Implementations/FullSystemBackup/BackupOptions.cs
@@ -0,0 +1,15 @@
+namespace Jellyfin.Server.Implementations.FullSystemBackup;
+
+/// <summary>
+/// Defines the optional contents of the backup archive.
+/// </summary>
+internal class BackupOptions
+{
+ public bool Metadata { get; set; }
+
+ public bool Trickplay { get; set; }
+
+ public bool Subtitles { get; set; }
+
+ public bool Database { get; set; }
+}
diff --git a/Jellyfin.Server.Implementations/FullSystemBackup/BackupService.cs b/Jellyfin.Server.Implementations/FullSystemBackup/BackupService.cs
new file mode 100644
index 000000000..e266d5a3b
--- /dev/null
+++ b/Jellyfin.Server.Implementations/FullSystemBackup/BackupService.cs
@@ -0,0 +1,512 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.IO.Compression;
+using System.Linq;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Text.Json.Serialization;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Database.Implementations;
+using Jellyfin.Server.Implementations.StorageHelpers;
+using Jellyfin.Server.Implementations.SystemBackupService;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.SystemBackupService;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Implementations.FullSystemBackup;
+
+/// <summary>
+/// Contains methods for creating and restoring backups.
+/// </summary>
+public class BackupService : IBackupService
+{
+ private const string ManifestEntryName = "manifest.json";
+ private readonly ILogger<BackupService> _logger;
+ private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
+ private readonly IServerApplicationHost _applicationHost;
+ private readonly IServerApplicationPaths _applicationPaths;
+ private readonly IJellyfinDatabaseProvider _jellyfinDatabaseProvider;
+ private readonly IHostApplicationLifetime _hostApplicationLifetime;
+ private static readonly JsonSerializerOptions _serializerSettings = new JsonSerializerOptions(JsonSerializerDefaults.General)
+ {
+ AllowTrailingCommas = true,
+ ReferenceHandler = ReferenceHandler.IgnoreCycles,
+ };
+
+ private readonly Version _backupEngineVersion = Version.Parse("0.1.0");
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BackupService"/> class.
+ /// </summary>
+ /// <param name="logger">A logger.</param>
+ /// <param name="dbProvider">A Database Factory.</param>
+ /// <param name="applicationHost">The Application host.</param>
+ /// <param name="applicationPaths">The application paths.</param>
+ /// <param name="jellyfinDatabaseProvider">The Jellyfin database Provider in use.</param>
+ /// <param name="applicationLifetime">The SystemManager.</param>
+ public BackupService(
+ ILogger<BackupService> logger,
+ IDbContextFactory<JellyfinDbContext> dbProvider,
+ IServerApplicationHost applicationHost,
+ IServerApplicationPaths applicationPaths,
+ IJellyfinDatabaseProvider jellyfinDatabaseProvider,
+ IHostApplicationLifetime applicationLifetime)
+ {
+ _logger = logger;
+ _dbProvider = dbProvider;
+ _applicationHost = applicationHost;
+ _applicationPaths = applicationPaths;
+ _jellyfinDatabaseProvider = jellyfinDatabaseProvider;
+ _hostApplicationLifetime = applicationLifetime;
+ }
+
+ /// <inheritdoc/>
+ public void ScheduleRestoreAndRestartServer(string archivePath)
+ {
+ _applicationHost.RestoreBackupPath = archivePath;
+ _applicationHost.ShouldRestart = true;
+ _applicationHost.NotifyPendingRestart();
+ _ = Task.Run(async () =>
+ {
+ await Task.Delay(500).ConfigureAwait(false);
+ _hostApplicationLifetime.StopApplication();
+ });
+ }
+
+ /// <inheritdoc/>
+ public async Task RestoreBackupAsync(string archivePath)
+ {
+ _logger.LogWarning("Begin restoring system to {BackupArchive}", archivePath); // Info isn't cutting it
+ if (!File.Exists(archivePath))
+ {
+ throw new FileNotFoundException($"Requested backup file '{archivePath}' does not exist.");
+ }
+
+ StorageHelper.TestCommonPathsForStorageCapacity(_applicationPaths, _logger);
+
+ var fileStream = File.OpenRead(archivePath);
+ await using (fileStream.ConfigureAwait(false))
+ {
+ using var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Read, false);
+ var zipArchiveEntry = zipArchive.GetEntry(ManifestEntryName);
+
+ if (zipArchiveEntry is null)
+ {
+ throw new NotSupportedException($"The loaded archive '{archivePath}' does not appear to be a Jellyfin backup as its missing the '{ManifestEntryName}'.");
+ }
+
+ BackupManifest? manifest;
+ var manifestStream = zipArchiveEntry.Open();
+ await using (manifestStream.ConfigureAwait(false))
+ {
+ manifest = await JsonSerializer.DeserializeAsync<BackupManifest>(manifestStream, _serializerSettings).ConfigureAwait(false);
+ }
+
+ if (manifest!.ServerVersion > _applicationHost.ApplicationVersion) // newer versions of Jellyfin should be able to load older versions as we have migrations.
+ {
+ throw new NotSupportedException($"The loaded archive '{archivePath}' is made for a newer version of Jellyfin ({manifest.ServerVersion}) and cannot be loaded in this version.");
+ }
+
+ if (!TestBackupVersionCompatibility(manifest.BackupEngineVersion))
+ {
+ throw new NotSupportedException($"The loaded archive '{archivePath}' is made for a newer version of Jellyfin ({manifest.ServerVersion}) and cannot be loaded in this version.");
+ }
+
+ void CopyDirectory(string source, string target)
+ {
+ source = Path.GetFullPath(source);
+ Directory.CreateDirectory(source);
+
+ foreach (var item in zipArchive.Entries)
+ {
+ var sanitizedSourcePath = Path.GetFullPath(item.FullName.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar);
+ if (!sanitizedSourcePath.StartsWith(target, StringComparison.Ordinal))
+ {
+ continue;
+ }
+
+ var targetPath = Path.Combine(source, sanitizedSourcePath[target.Length..].Trim('/'));
+ _logger.LogInformation("Restore and override {File}", targetPath);
+ item.ExtractToFile(targetPath);
+ }
+ }
+
+ CopyDirectory(_applicationPaths.ConfigurationDirectoryPath, "Config/");
+ CopyDirectory(_applicationPaths.DataPath, "Data/");
+ CopyDirectory(_applicationPaths.RootFolderPath, "Root/");
+
+ if (manifest.Options.Database)
+ {
+ _logger.LogInformation("Begin restoring Database");
+ var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
+ await using (dbContext.ConfigureAwait(false))
+ {
+ // restore migration history manually
+ var historyEntry = zipArchive.GetEntry($"Database\\{nameof(HistoryRow)}.json");
+ if (historyEntry is null)
+ {
+ _logger.LogInformation("No backup of the history table in archive. This is required for Jellyfin operation");
+ throw new InvalidOperationException("Cannot restore backup that has no History data.");
+ }
+
+ HistoryRow[] historyEntries;
+ var historyArchive = historyEntry.Open();
+ await using (historyArchive.ConfigureAwait(false))
+ {
+ historyEntries = await JsonSerializer.DeserializeAsync<HistoryRow[]>(historyArchive).ConfigureAwait(false) ??
+ throw new InvalidOperationException("Cannot restore backup that has no History data.");
+ }
+
+ var historyRepository = dbContext.GetService<IHistoryRepository>();
+ await historyRepository.CreateIfNotExistsAsync().ConfigureAwait(false);
+ foreach (var item in historyEntries)
+ {
+ var insertScript = historyRepository.GetInsertScript(item);
+ await dbContext.Database.ExecuteSqlRawAsync(insertScript).ConfigureAwait(false);
+ }
+
+ dbContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
+ var entityTypes = typeof(JellyfinDbContext).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
+ .Where(e => e.PropertyType.IsAssignableTo(typeof(IQueryable)))
+ .Select(e => (Type: e, Set: e.GetValue(dbContext) as IQueryable))
+ .ToArray();
+
+ var tableNames = entityTypes.Select(f => dbContext.Model.FindEntityType(f.Type.PropertyType.GetGenericArguments()[0])!.GetSchemaQualifiedTableName()!);
+ _logger.LogInformation("Begin purging database");
+ await _jellyfinDatabaseProvider.PurgeDatabase(dbContext, tableNames).ConfigureAwait(false);
+ _logger.LogInformation("Database Purged");
+
+ foreach (var entityType in entityTypes)
+ {
+ _logger.LogInformation("Read backup of {Table}", entityType.Type.Name);
+
+ var zipEntry = zipArchive.GetEntry($"Database\\{entityType.Type.Name}.json");
+ if (zipEntry is null)
+ {
+ _logger.LogInformation("No backup of expected table {Table} is present in backup. Continue anyway.", entityType.Type.Name);
+ continue;
+ }
+
+ var zipEntryStream = zipEntry.Open();
+ await using (zipEntryStream.ConfigureAwait(false))
+ {
+ _logger.LogInformation("Restore backup of {Table}", entityType.Type.Name);
+ var records = 0;
+ await foreach (var item in JsonSerializer.DeserializeAsyncEnumerable<JsonObject>(zipEntryStream, _serializerSettings).ConfigureAwait(false)!)
+ {
+ var entity = item.Deserialize(entityType.Type.PropertyType.GetGenericArguments()[0]);
+ if (entity is null)
+ {
+ throw new InvalidOperationException($"Cannot deserialize entity '{item}'");
+ }
+
+ try
+ {
+ records++;
+ dbContext.Add(entity);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Could not store entity {Entity} continue anyway.", item);
+ }
+ }
+
+ _logger.LogInformation("Prepared to restore {Number} entries for {Table}", records, entityType.Type.Name);
+ }
+ }
+
+ _logger.LogInformation("Try restore Database");
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
+ _logger.LogInformation("Restored database.");
+ }
+ }
+
+ _logger.LogInformation("Restored Jellyfin system from {Date}.", manifest.DateCreated);
+ }
+ }
+
+ private bool TestBackupVersionCompatibility(Version backupEngineVersion)
+ {
+ if (backupEngineVersion == _backupEngineVersion)
+ {
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <inheritdoc/>
+ public async Task<BackupManifestDto> CreateBackupAsync(BackupOptionsDto backupOptions)
+ {
+ var manifest = new BackupManifest()
+ {
+ DateCreated = DateTime.UtcNow,
+ ServerVersion = _applicationHost.ApplicationVersion,
+ DatabaseTables = null!,
+ BackupEngineVersion = _backupEngineVersion,
+ Options = Map(backupOptions)
+ };
+
+ await _jellyfinDatabaseProvider.RunScheduledOptimisation(CancellationToken.None).ConfigureAwait(false);
+
+ var backupFolder = Path.Combine(_applicationPaths.BackupPath);
+
+ if (!Directory.Exists(backupFolder))
+ {
+ Directory.CreateDirectory(backupFolder);
+ }
+
+ var backupStorageSpace = StorageHelper.GetFreeSpaceOf(_applicationPaths.BackupPath);
+
+ const long FiveGigabyte = 5_368_709_115;
+ if (backupStorageSpace.FreeSpace < FiveGigabyte)
+ {
+ throw new InvalidOperationException($"The backup directory '{backupStorageSpace.Path}' does not have at least '{StorageHelper.HumanizeStorageSize(FiveGigabyte)}' free space. Cannot create backup.");
+ }
+
+ var backupPath = Path.Combine(backupFolder, $"jellyfin-backup-{manifest.DateCreated.ToLocalTime():yyyyMMddHHmmss}.zip");
+ _logger.LogInformation("Attempt to create a new backup at {BackupPath}", backupPath);
+ var fileStream = File.OpenWrite(backupPath);
+ await using (fileStream.ConfigureAwait(false))
+ using (var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Create, false))
+ {
+ _logger.LogInformation("Start backup process.");
+ var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
+ await using (dbContext.ConfigureAwait(false))
+ {
+ dbContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
+ static IAsyncEnumerable<object> GetValues(IQueryable dbSet, Type type)
+ {
+ var method = dbSet.GetType().GetMethod(nameof(DbSet<object>.AsAsyncEnumerable))!;
+ var enumerable = method.Invoke(dbSet, null)!;
+ return (IAsyncEnumerable<object>)enumerable;
+ }
+
+ // include the migration history as well
+ var historyRepository = dbContext.GetService<IHistoryRepository>();
+ var migrations = await historyRepository.GetAppliedMigrationsAsync().ConfigureAwait(false);
+
+ ICollection<(Type Type, Func<IAsyncEnumerable<object>> ValueFactory)> entityTypes = [
+ .. typeof(JellyfinDbContext)
+ .GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
+ .Where(e => e.PropertyType.IsAssignableTo(typeof(IQueryable)))
+ .Select(e => (Type: e.PropertyType, ValueFactory: new Func<IAsyncEnumerable<object>>(() => GetValues((IQueryable)e.GetValue(dbContext)!, e.PropertyType)))),
+ (Type: typeof(HistoryRow), ValueFactory: new Func<IAsyncEnumerable<object>>(() => migrations.ToAsyncEnumerable()))
+ ];
+ manifest.DatabaseTables = entityTypes.Select(e => e.Type.Name).ToArray();
+ var transaction = await dbContext.Database.BeginTransactionAsync().ConfigureAwait(false);
+
+ await using (transaction.ConfigureAwait(false))
+ {
+ _logger.LogInformation("Begin Database backup");
+
+ foreach (var entityType in entityTypes)
+ {
+ _logger.LogInformation("Begin backup of entity {Table}", entityType.Type.Name);
+ var zipEntry = zipArchive.CreateEntry($"Database\\{entityType.Type.Name}.json");
+ var entities = 0;
+ var zipEntryStream = zipEntry.Open();
+ await using (zipEntryStream.ConfigureAwait(false))
+ {
+ var jsonSerializer = new Utf8JsonWriter(zipEntryStream);
+ await using (jsonSerializer.ConfigureAwait(false))
+ {
+ jsonSerializer.WriteStartArray();
+
+ var set = entityType.ValueFactory().ConfigureAwait(false);
+ await foreach (var item in set.ConfigureAwait(false))
+ {
+ entities++;
+ try
+ {
+ JsonSerializer.SerializeToDocument(item, _serializerSettings).WriteTo(jsonSerializer);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Could not load entity {Entity}", item);
+ throw;
+ }
+ }
+
+ jsonSerializer.WriteEndArray();
+ }
+ }
+
+ _logger.LogInformation("backup of entity {Table} with {Number} created", entityType.Type.Name, entities);
+ }
+ }
+ }
+
+ _logger.LogInformation("Backup of folder {Table}", _applicationPaths.ConfigurationDirectoryPath);
+ foreach (var item in Directory.EnumerateFiles(_applicationPaths.ConfigurationDirectoryPath, "*.xml", SearchOption.TopDirectoryOnly)
+ .Union(Directory.EnumerateFiles(_applicationPaths.ConfigurationDirectoryPath, "*.json", SearchOption.TopDirectoryOnly)))
+ {
+ zipArchive.CreateEntryFromFile(item, Path.Combine("Config", Path.GetFileName(item)));
+ }
+
+ void CopyDirectory(string source, string target, string filter = "*")
+ {
+ if (!Directory.Exists(source))
+ {
+ return;
+ }
+
+ _logger.LogInformation("Backup of folder {Table}", source);
+
+ foreach (var item in Directory.EnumerateFiles(source, filter, SearchOption.AllDirectories))
+ {
+ zipArchive.CreateEntryFromFile(item, Path.Combine(target, item[..source.Length].Trim('\\')));
+ }
+ }
+
+ CopyDirectory(Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "users"), Path.Combine("Config", "users"));
+ CopyDirectory(Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "ScheduledTasks"), Path.Combine("Config", "ScheduledTasks"));
+ CopyDirectory(Path.Combine(_applicationPaths.RootFolderPath), "Root");
+ CopyDirectory(Path.Combine(_applicationPaths.DataPath, "collections"), Path.Combine("Data", "collections"));
+ CopyDirectory(Path.Combine(_applicationPaths.DataPath, "playlists"), Path.Combine("Data", "playlists"));
+ CopyDirectory(Path.Combine(_applicationPaths.DataPath, "ScheduledTasks"), Path.Combine("Data", "ScheduledTasks"));
+ if (backupOptions.Subtitles)
+ {
+ CopyDirectory(Path.Combine(_applicationPaths.DataPath, "subtitles"), Path.Combine("Data", "subtitles"));
+ }
+
+ if (backupOptions.Trickplay)
+ {
+ CopyDirectory(Path.Combine(_applicationPaths.DataPath, "trickplay"), Path.Combine("Data", "trickplay"));
+ }
+
+ if (backupOptions.Metadata)
+ {
+ CopyDirectory(Path.Combine(_applicationPaths.InternalMetadataPath), Path.Combine("Data", "metadata"));
+ }
+
+ var manifestStream = zipArchive.CreateEntry(ManifestEntryName).Open();
+ await using (manifestStream.ConfigureAwait(false))
+ {
+ await JsonSerializer.SerializeAsync(manifestStream, manifest).ConfigureAwait(false);
+ }
+ }
+
+ _logger.LogInformation("Backup created");
+ return Map(manifest, backupPath);
+ }
+
+ /// <inheritdoc/>
+ public async Task<BackupManifestDto?> GetBackupManifest(string archivePath)
+ {
+ if (!File.Exists(archivePath))
+ {
+ return null;
+ }
+
+ BackupManifest? manifest;
+ try
+ {
+ manifest = await GetManifest(archivePath).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Tried to load archive from {Path} but failed.", archivePath);
+ return null;
+ }
+
+ if (manifest is null)
+ {
+ return null;
+ }
+
+ return Map(manifest, archivePath);
+ }
+
+ /// <inheritdoc/>
+ public async Task<BackupManifestDto[]> EnumerateBackups()
+ {
+ if (!Directory.Exists(_applicationPaths.BackupPath))
+ {
+ return [];
+ }
+
+ var archives = Directory.EnumerateFiles(_applicationPaths.BackupPath, "*.zip");
+ var manifests = new List<BackupManifestDto>();
+ foreach (var item in archives)
+ {
+ try
+ {
+ var manifest = await GetManifest(item).ConfigureAwait(false);
+
+ if (manifest is null)
+ {
+ continue;
+ }
+
+ manifests.Add(Map(manifest, item));
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Could not load {BackupArchive} path.", item);
+ }
+ }
+
+ return manifests.ToArray();
+ }
+
+ private static async ValueTask<BackupManifest?> GetManifest(string archivePath)
+ {
+ var archiveStream = File.OpenRead(archivePath);
+ await using (archiveStream.ConfigureAwait(false))
+ {
+ using var zipStream = new ZipArchive(archiveStream, ZipArchiveMode.Read);
+ var manifestEntry = zipStream.GetEntry(ManifestEntryName);
+ if (manifestEntry is null)
+ {
+ return null;
+ }
+
+ var manifestStream = manifestEntry.Open();
+ await using (manifestStream.ConfigureAwait(false))
+ {
+ return await JsonSerializer.DeserializeAsync<BackupManifest>(manifestStream, _serializerSettings).ConfigureAwait(false);
+ }
+ }
+ }
+
+ private static BackupManifestDto Map(BackupManifest manifest, string path)
+ {
+ return new BackupManifestDto()
+ {
+ BackupEngineVersion = manifest.BackupEngineVersion,
+ DateCreated = manifest.DateCreated,
+ ServerVersion = manifest.ServerVersion,
+ Path = path,
+ Options = Map(manifest.Options)
+ };
+ }
+
+ private static BackupOptionsDto Map(BackupOptions options)
+ {
+ return new BackupOptionsDto()
+ {
+ Metadata = options.Metadata,
+ Subtitles = options.Subtitles,
+ Trickplay = options.Trickplay,
+ Database = options.Database
+ };
+ }
+
+ private static BackupOptions Map(BackupOptionsDto options)
+ {
+ return new BackupOptions()
+ {
+ Metadata = options.Metadata,
+ Subtitles = options.Subtitles,
+ Trickplay = options.Trickplay,
+ Database = options.Database
+ };
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Item/BaseItemRepository.cs b/Jellyfin.Server.Implementations/Item/BaseItemRepository.cs
index b0a36b3ae..3efcb6dd3 100644
--- a/Jellyfin.Server.Implementations/Item/BaseItemRepository.cs
+++ b/Jellyfin.Server.Implementations/Item/BaseItemRepository.cs
@@ -9,6 +9,7 @@ using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
+using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Text.Json;
@@ -19,6 +20,7 @@ using Jellyfin.Database.Implementations.Entities;
using Jellyfin.Database.Implementations.Enums;
using Jellyfin.Extensions;
using Jellyfin.Extensions.Json;
+using Jellyfin.Server.Implementations.Extensions;
using MediaBrowser.Common;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Channels;
@@ -66,7 +68,7 @@ public sealed class BaseItemRepository
private static readonly IReadOnlyList<ItemValueType> _getArtistValueTypes = [ItemValueType.Artist];
private static readonly IReadOnlyList<ItemValueType> _getAlbumArtistValueTypes = [ItemValueType.AlbumArtist];
private static readonly IReadOnlyList<ItemValueType> _getStudiosValueTypes = [ItemValueType.Studios];
- private static readonly IReadOnlyList<ItemValueType> _getGenreValueTypes = [ItemValueType.Studios];
+ private static readonly IReadOnlyList<ItemValueType> _getGenreValueTypes = [ItemValueType.Genre];
/// <summary>
/// Initializes a new instance of the <see cref="BaseItemRepository"/> class.
@@ -112,6 +114,7 @@ public sealed class BaseItemRepository
context.ItemDisplayPreferences.Where(e => e.ItemId == id).ExecuteDelete();
context.ItemValues.Where(e => e.BaseItemsMap!.Count == 0).ExecuteDelete();
context.ItemValuesMap.Where(e => e.ItemId == id).ExecuteDelete();
+ context.KeyframeData.Where(e => e.ItemId == id).ExecuteDelete();
context.MediaSegments.Where(e => e.ItemId == id).ExecuteDelete();
context.MediaStreamInfos.Where(e => e.ItemId == id).ExecuteDelete();
context.PeopleBaseItemMap.Where(e => e.ItemId == id).ExecuteDelete();
@@ -145,37 +148,37 @@ public sealed class BaseItemRepository
}
/// <inheritdoc />
- public QueryResult<(BaseItemDto Item, ItemCounts ItemCounts)> GetAllArtists(InternalItemsQuery filter)
+ public QueryResult<(BaseItemDto Item, ItemCounts? ItemCounts)> GetAllArtists(InternalItemsQuery filter)
{
return GetItemValues(filter, _getAllArtistsValueTypes, _itemTypeLookup.BaseItemKindNames[BaseItemKind.MusicArtist]);
}
/// <inheritdoc />
- public QueryResult<(BaseItemDto Item, ItemCounts ItemCounts)> GetArtists(InternalItemsQuery filter)
+ public QueryResult<(BaseItemDto Item, ItemCounts? ItemCounts)> GetArtists(InternalItemsQuery filter)
{
return GetItemValues(filter, _getArtistValueTypes, _itemTypeLookup.BaseItemKindNames[BaseItemKind.MusicArtist]);
}
/// <inheritdoc />
- public QueryResult<(BaseItemDto Item, ItemCounts ItemCounts)> GetAlbumArtists(InternalItemsQuery filter)
+ public QueryResult<(BaseItemDto Item, ItemCounts? ItemCounts)> GetAlbumArtists(InternalItemsQuery filter)
{
return GetItemValues(filter, _getAlbumArtistValueTypes, _itemTypeLookup.BaseItemKindNames[BaseItemKind.MusicArtist]);
}
/// <inheritdoc />
- public QueryResult<(BaseItemDto Item, ItemCounts ItemCounts)> GetStudios(InternalItemsQuery filter)
+ public QueryResult<(BaseItemDto Item, ItemCounts? ItemCounts)> GetStudios(InternalItemsQuery filter)
{
return GetItemValues(filter, _getStudiosValueTypes, _itemTypeLookup.BaseItemKindNames[BaseItemKind.Studio]);
}
/// <inheritdoc />
- public QueryResult<(BaseItemDto Item, ItemCounts ItemCounts)> GetGenres(InternalItemsQuery filter)
+ public QueryResult<(BaseItemDto Item, ItemCounts? ItemCounts)> GetGenres(InternalItemsQuery filter)
{
return GetItemValues(filter, _getGenreValueTypes, _itemTypeLookup.BaseItemKindNames[BaseItemKind.Genre]);
}
/// <inheritdoc />
- public QueryResult<(BaseItemDto Item, ItemCounts ItemCounts)> GetMusicGenres(InternalItemsQuery filter)
+ public QueryResult<(BaseItemDto Item, ItemCounts? ItemCounts)> GetMusicGenres(InternalItemsQuery filter)
{
return GetItemValues(filter, _getGenreValueTypes, _itemTypeLookup.BaseItemKindNames[BaseItemKind.MusicGenre]);
}
@@ -399,7 +402,8 @@ public sealed class BaseItemRepository
private IQueryable<BaseItemEntity> PrepareItemQuery(JellyfinDbContext context, InternalItemsQuery filter)
{
- IQueryable<BaseItemEntity> dbQuery = context.BaseItems.AsNoTracking().AsSplitQuery()
+ IQueryable<BaseItemEntity> dbQuery = context.BaseItems.AsNoTracking();
+ dbQuery = dbQuery.AsSingleQuery()
.Include(e => e.TrailerTypes)
.Include(e => e.Provider)
.Include(e => e.LockedFields);
@@ -450,11 +454,9 @@ public sealed class BaseItemRepository
var images = item.ImageInfos.Select(e => Map(item.Id, e));
using var context = _dbProvider.CreateDbContext();
- using var transaction = context.Database.BeginTransaction();
context.BaseItemImageInfos.Where(e => e.ItemId == item.Id).ExecuteDelete();
context.BaseItemImageInfos.AddRange(images);
context.SaveChanges();
- transaction.Commit();
}
/// <inheritdoc />
@@ -484,17 +486,19 @@ public sealed class BaseItemRepository
tuples.Add((item, ancestorIds, topParent, userdataKey, inheritedTags));
}
- var localItemValueCache = new Dictionary<(int MagicNumber, string Value), Guid>();
-
using var context = _dbProvider.CreateDbContext();
using var transaction = context.Database.BeginTransaction();
+
+ var ids = tuples.Select(f => f.Item.Id).ToArray();
+ var existingItems = context.BaseItems.Where(e => ids.Contains(e.Id)).Select(f => f.Id).ToArray();
+
foreach (var item in tuples)
{
var entity = Map(item.Item);
// TODO: refactor this "inconsistency"
entity.TopParentId = item.TopParent?.Id;
- if (!context.BaseItems.Any(e => e.Id == entity.Id))
+ if (!existingItems.Any(e => e == entity.Id))
{
context.BaseItems.Add(entity);
}
@@ -503,59 +507,98 @@ public sealed class BaseItemRepository
context.BaseItemProviders.Where(e => e.ItemId == entity.Id).ExecuteDelete();
context.BaseItems.Attach(entity).State = EntityState.Modified;
}
+ }
- context.AncestorIds.Where(e => e.ItemId == entity.Id).ExecuteDelete();
- if (item.Item.SupportsAncestors && item.AncestorIds != null)
+ context.SaveChanges();
+
+ var itemValueMaps = tuples
+ .Select(e => (Item: e.Item, Values: GetItemValuesToSave(e.Item, e.InheritedTags)))
+ .ToArray();
+ var allListedItemValues = itemValueMaps
+ .SelectMany(f => f.Values)
+ .Distinct()
+ .ToArray();
+ var existingValues = context.ItemValues
+ .Select(e => new
{
- foreach (var ancestorId in item.AncestorIds)
- {
- if (!context.BaseItems.Any(f => f.Id == ancestorId))
- {
- continue;
- }
+ item = e,
+ Key = e.Type + "+" + e.Value
+ })
+ .Where(f => allListedItemValues.Select(e => $"{(int)e.MagicNumber}+{e.Value}").Contains(f.Key))
+ .Select(e => e.item)
+ .ToArray();
+ var missingItemValues = allListedItemValues.Except(existingValues.Select(f => (MagicNumber: f.Type, f.Value))).Select(f => new ItemValue()
+ {
+ CleanValue = GetCleanValue(f.Value),
+ ItemValueId = Guid.NewGuid(),
+ Type = f.MagicNumber,
+ Value = f.Value
+ }).ToArray();
+ context.ItemValues.AddRange(missingItemValues);
+ context.SaveChanges();
+
+ var itemValuesStore = existingValues.Concat(missingItemValues).ToArray();
+ var valueMap = itemValueMaps
+ .Select(f => (Item: f.Item, Values: f.Values.Select(e => itemValuesStore.First(g => g.Value == e.Value && g.Type == e.MagicNumber)).ToArray()))
+ .ToArray();
- context.AncestorIds.Add(new AncestorId()
+ var mappedValues = context.ItemValuesMap.Where(e => ids.Contains(e.ItemId)).ToList();
+
+ foreach (var item in valueMap)
+ {
+ var itemMappedValues = mappedValues.Where(e => e.ItemId == item.Item.Id).ToList();
+ foreach (var itemValue in item.Values)
+ {
+ var existingItem = itemMappedValues.FirstOrDefault(f => f.ItemValueId == itemValue.ItemValueId);
+ if (existingItem is null)
+ {
+ context.ItemValuesMap.Add(new ItemValueMap()
{
- ParentItemId = ancestorId,
- ItemId = entity.Id,
Item = null!,
- ParentItem = null!
+ ItemId = item.Item.Id,
+ ItemValue = null!,
+ ItemValueId = itemValue.ItemValueId
});
}
- }
-
- // Never save duplicate itemValues as they are now mapped anyway.
- var itemValuesToSave = GetItemValuesToSave(item.Item, item.InheritedTags).DistinctBy(e => (GetCleanValue(e.Value), e.MagicNumber));
- context.ItemValuesMap.Where(e => e.ItemId == entity.Id).ExecuteDelete();
- foreach (var itemValue in itemValuesToSave)
- {
- if (!localItemValueCache.TryGetValue(itemValue, out var refValue))
+ else
{
- refValue = context.ItemValues
- .Where(f => f.CleanValue == GetCleanValue(itemValue.Value) && (int)f.Type == itemValue.MagicNumber)
- .Select(e => e.ItemValueId)
- .FirstOrDefault();
+ // map exists, remove from list so its been handled.
+ itemMappedValues.Remove(existingItem);
}
+ }
+
+ // all still listed values are not in the new list so remove them.
+ context.ItemValuesMap.RemoveRange(itemMappedValues);
+ }
+
+ context.SaveChanges();
- if (refValue.IsEmpty())
+ foreach (var item in tuples)
+ {
+ if (item.Item.SupportsAncestors && item.AncestorIds != null)
+ {
+ var existingAncestorIds = context.AncestorIds.Where(e => e.ItemId == item.Item.Id).ToList();
+ var validAncestorIds = context.BaseItems.Where(e => item.AncestorIds.Contains(e.Id)).Select(f => f.Id).ToArray();
+ foreach (var ancestorId in validAncestorIds)
{
- context.ItemValues.Add(new ItemValue()
+ var existingAncestorId = existingAncestorIds.FirstOrDefault(e => e.ParentItemId == ancestorId);
+ if (existingAncestorId is null)
{
- CleanValue = GetCleanValue(itemValue.Value),
- Type = (ItemValueType)itemValue.MagicNumber,
- ItemValueId = refValue = Guid.NewGuid(),
- Value = itemValue.Value
- });
- localItemValueCache[itemValue] = refValue;
+ context.AncestorIds.Add(new AncestorId()
+ {
+ ParentItemId = ancestorId,
+ ItemId = item.Item.Id,
+ Item = null!,
+ ParentItem = null!
+ });
+ }
+ else
+ {
+ existingAncestorIds.Remove(existingAncestorId);
+ }
}
- context.ItemValuesMap.Add(new ItemValueMap()
- {
- Item = null!,
- ItemId = entity.Id,
- ItemValue = null!,
- ItemValueId = refValue
- });
+ context.AncestorIds.RemoveRange(existingAncestorIds);
}
}
@@ -617,6 +660,7 @@ public sealed class BaseItemRepository
dto.PreferredMetadataCountryCode = entity.PreferredMetadataCountryCode;
dto.IsInMixedFolder = entity.IsInMixedFolder;
dto.InheritedParentalRatingValue = entity.InheritedParentalRatingValue;
+ dto.InheritedParentalRatingSubValue = entity.InheritedParentalRatingSubValue;
dto.CriticRating = entity.CriticRating;
dto.PresentationUniqueKey = entity.PresentationUniqueKey;
dto.OriginalTitle = entity.OriginalTitle;
@@ -781,6 +825,7 @@ public sealed class BaseItemRepository
entity.PreferredMetadataCountryCode = dto.PreferredMetadataCountryCode;
entity.IsInMixedFolder = dto.IsInMixedFolder;
entity.InheritedParentalRatingValue = dto.InheritedParentalRatingValue;
+ entity.InheritedParentalRatingSubValue = dto.InheritedParentalRatingSubValue;
entity.CriticRating = dto.CriticRating;
entity.PresentationUniqueKey = dto.PresentationUniqueKey;
entity.OriginalTitle = dto.OriginalTitle;
@@ -993,7 +1038,7 @@ public sealed class BaseItemRepository
return Map(baseItemEntity, dto, appHost);
}
- private QueryResult<(BaseItemDto Item, ItemCounts ItemCounts)> GetItemValues(InternalItemsQuery filter, IReadOnlyList<ItemValueType> itemValueTypes, string returnType)
+ private QueryResult<(BaseItemDto Item, ItemCounts? ItemCounts)> GetItemValues(InternalItemsQuery filter, IReadOnlyList<ItemValueType> itemValueTypes, string returnType)
{
ArgumentNullException.ThrowIfNull(filter);
@@ -1004,20 +1049,59 @@ public sealed class BaseItemRepository
using var context = _dbProvider.CreateDbContext();
- var query = TranslateQuery(context.BaseItems.AsNoTracking(), context, filter);
+ var innerQueryFilter = TranslateQuery(context.BaseItems, context, new InternalItemsQuery(filter.User)
+ {
+ ExcludeItemTypes = filter.ExcludeItemTypes,
+ IncludeItemTypes = filter.IncludeItemTypes,
+ MediaTypes = filter.MediaTypes,
+ AncestorIds = filter.AncestorIds,
+ ItemIds = filter.ItemIds,
+ TopParentIds = filter.TopParentIds,
+ ParentId = filter.ParentId,
+ IsAiring = filter.IsAiring,
+ IsMovie = filter.IsMovie,
+ IsSports = filter.IsSports,
+ IsKids = filter.IsKids,
+ IsNews = filter.IsNews,
+ IsSeries = filter.IsSeries
+ });
- query = query.Where(e => e.Type == returnType);
- // this does not seem to be nesseary but it does not make any sense why this isn't working.
- // && e.ItemValues!.Any(f => e.CleanName == f.ItemValue.CleanValue && itemValueTypes.Any(w => (ItemValueType)w == f.ItemValue.Type)));
+ var innerQuery = PrepareItemQuery(context, filter)
+ .Where(e => e.Type == returnType)
+ .Where(e => context.ItemValues!
+ .Where(f => itemValueTypes.Contains(f.Type))
+ .Where(f => innerQueryFilter.Any(g => f.BaseItemsMap!.Any(w => w.ItemId == g.Id)))
+ .Select(f => f.CleanValue)
+ .Contains(e.CleanName));
+
+ var outerQueryFilter = new InternalItemsQuery(filter.User)
+ {
+ IsPlayed = filter.IsPlayed,
+ IsFavorite = filter.IsFavorite,
+ IsFavoriteOrLiked = filter.IsFavoriteOrLiked,
+ IsLiked = filter.IsLiked,
+ IsLocked = filter.IsLocked,
+ NameLessThan = filter.NameLessThan,
+ NameStartsWith = filter.NameStartsWith,
+ NameStartsWithOrGreater = filter.NameStartsWithOrGreater,
+ Tags = filter.Tags,
+ OfficialRatings = filter.OfficialRatings,
+ StudioIds = filter.StudioIds,
+ GenreIds = filter.GenreIds,
+ Genres = filter.Genres,
+ Years = filter.Years,
+ NameContains = filter.NameContains,
+ SearchTerm = filter.SearchTerm,
+ ExcludeItemIds = filter.ExcludeItemIds
+ };
- if (filter.OrderBy.Count != 0
- || !string.IsNullOrEmpty(filter.SearchTerm))
- {
- query = ApplyOrder(query, filter);
- }
- else
+ var query = TranslateQuery(innerQuery, context, outerQueryFilter)
+ .GroupBy(e => e.PresentationUniqueKey);
+
+ var result = new QueryResult<(BaseItemDto, ItemCounts?)>();
+ if (filter.EnableTotalRecordCount)
{
- query = query.OrderBy(e => e.SortName);
+ result.TotalRecordCount = query.Count();
}
if (filter.Limit.HasValue || filter.StartIndex.HasValue)
@@ -1035,41 +1119,84 @@ public sealed class BaseItemRepository
}
}
- var result = new QueryResult<(BaseItemDto, ItemCounts)>();
- if (filter.EnableTotalRecordCount)
- {
- result.TotalRecordCount = query.GroupBy(e => e.PresentationUniqueKey).Select(e => e.First()).Count();
- }
-
- var seriesTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Series];
- var movieTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Movie];
- var episodeTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Episode];
- var musicAlbumTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.MusicAlbum];
- var musicArtistTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.MusicArtist];
- var audioTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Audio];
- var trailerTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Trailer];
+ IQueryable<BaseItemEntity>? itemCountQuery = null;
- var resultQuery = query.Select(e => new
+ if (filter.IncludeItemTypes.Length > 0)
{
- item = e,
- // TODO: This is bad refactor!
- itemCount = new ItemCounts()
+ // if we are to include more then one type, sub query those items beforehand.
+
+ var typeSubQuery = new InternalItemsQuery(filter.User)
{
- SeriesCount = e.ItemValues!.Count(f => f.Item.Type == seriesTypeName),
- EpisodeCount = e.ItemValues!.Count(f => f.Item.Type == episodeTypeName),
- MovieCount = e.ItemValues!.Count(f => f.Item.Type == movieTypeName),
- AlbumCount = e.ItemValues!.Count(f => f.Item.Type == musicAlbumTypeName),
- ArtistCount = e.ItemValues!.Count(f => f.Item.Type == musicArtistTypeName),
- SongCount = e.ItemValues!.Count(f => f.Item.Type == audioTypeName),
- TrailerCount = e.ItemValues!.Count(f => f.Item.Type == trailerTypeName),
- }
- });
+ ExcludeItemTypes = filter.ExcludeItemTypes,
+ IncludeItemTypes = filter.IncludeItemTypes,
+ MediaTypes = filter.MediaTypes,
+ AncestorIds = filter.AncestorIds,
+ ExcludeItemIds = filter.ExcludeItemIds,
+ ItemIds = filter.ItemIds,
+ TopParentIds = filter.TopParentIds,
+ ParentId = filter.ParentId,
+ IsPlayed = filter.IsPlayed
+ };
- result.StartIndex = filter.StartIndex ?? 0;
- result.Items = resultQuery.ToArray().Where(e => e is not null).Select(e =>
+ itemCountQuery = TranslateQuery(context.BaseItems.AsNoTracking(), context, typeSubQuery)
+ .Where(e => e.ItemValues!.Any(f => itemValueTypes!.Contains(f.ItemValue.Type)));
+
+ var seriesTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Series];
+ var movieTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Movie];
+ var episodeTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Episode];
+ var musicAlbumTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.MusicAlbum];
+ var musicArtistTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.MusicArtist];
+ var audioTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Audio];
+ var trailerTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Trailer];
+
+ var resultQuery = query.Select(e => new
+ {
+ item = e.AsQueryable()
+ .Include(e => e.TrailerTypes)
+ .Include(e => e.Provider)
+ .Include(e => e.LockedFields)
+ .Include(e => e.Images)
+ .AsSingleQuery().First(),
+ // TODO: This is bad refactor!
+ itemCount = new ItemCounts()
+ {
+ SeriesCount = itemCountQuery!.Count(f => f.Type == seriesTypeName),
+ EpisodeCount = itemCountQuery!.Count(f => f.Type == episodeTypeName),
+ MovieCount = itemCountQuery!.Count(f => f.Type == movieTypeName),
+ AlbumCount = itemCountQuery!.Count(f => f.Type == musicAlbumTypeName),
+ ArtistCount = itemCountQuery!.Count(f => f.Type == musicArtistTypeName),
+ SongCount = itemCountQuery!.Count(f => f.Type == audioTypeName),
+ TrailerCount = itemCountQuery!.Count(f => f.Type == trailerTypeName),
+ }
+ });
+
+ result.StartIndex = filter.StartIndex ?? 0;
+ result.Items =
+ [
+ .. resultQuery
+ .AsEnumerable()
+ .Where(e => e is not null)
+ .Select(e =>
+ {
+ return (DeserialiseBaseItem(e.item, filter.SkipDeserialization), e.itemCount);
+ })
+ ];
+ }
+ else
{
- return (DeserialiseBaseItem(e.item, filter.SkipDeserialization), e.itemCount);
- }).ToArray();
+ result.StartIndex = filter.StartIndex ?? 0;
+ result.Items =
+ [
+ .. query
+ .Select(e => e.First())
+ .AsEnumerable()
+ .Where(e => e is not null)
+ .Select<BaseItemEntity, (BaseItemDto, ItemCounts?)>(e =>
+ {
+ return (DeserialiseBaseItem(e, filter.SkipDeserialization), null);
+ })
+ ];
+ }
return result;
}
@@ -1097,27 +1224,27 @@ public sealed class BaseItemRepository
return value.RemoveDiacritics().ToLowerInvariant();
}
- private List<(int MagicNumber, string Value)> GetItemValuesToSave(BaseItemDto item, List<string> inheritedTags)
+ private List<(ItemValueType MagicNumber, string Value)> GetItemValuesToSave(BaseItemDto item, List<string> inheritedTags)
{
- var list = new List<(int, string)>();
+ var list = new List<(ItemValueType, string)>();
if (item is IHasArtist hasArtist)
{
- list.AddRange(hasArtist.Artists.Select(i => (0, i)));
+ list.AddRange(hasArtist.Artists.Select(i => ((ItemValueType)0, i)));
}
if (item is IHasAlbumArtist hasAlbumArtist)
{
- list.AddRange(hasAlbumArtist.AlbumArtists.Select(i => (1, i)));
+ list.AddRange(hasAlbumArtist.AlbumArtists.Select(i => (ItemValueType.AlbumArtist, i)));
}
- list.AddRange(item.Genres.Select(i => (2, i)));
- list.AddRange(item.Studios.Select(i => (3, i)));
- list.AddRange(item.Tags.Select(i => (4, i)));
+ list.AddRange(item.Genres.Select(i => (ItemValueType.Genre, i)));
+ list.AddRange(item.Studios.Select(i => (ItemValueType.Studios, i)));
+ list.AddRange(item.Tags.Select(i => (ItemValueType.Tags, i)));
// keywords was 5
- list.AddRange(inheritedTags.Select(i => (6, i)));
+ list.AddRange(inheritedTags.Select(i => (ItemValueType.InheritedTags, i)));
// Remove all invalid values.
list.RemoveAll(i => string.IsNullOrWhiteSpace(i.Item2));
@@ -1252,7 +1379,7 @@ public sealed class BaseItemRepository
}
else if (orderBy.Count == 0)
{
- return query;
+ return query.OrderBy(e => e.SortName);
}
IOrderedQueryable<BaseItemEntity>? orderedQuery = null;
@@ -1304,34 +1431,39 @@ public sealed class BaseItemRepository
JellyfinDbContext context,
InternalItemsQuery filter)
{
+ const int HDWidth = 1200;
+ const int UHDWidth = 3800;
+ const int UHDHeight = 2100;
+
var minWidth = filter.MinWidth;
var maxWidth = filter.MaxWidth;
var now = DateTime.UtcNow;
- if (filter.IsHD.HasValue)
+ if (filter.IsHD.HasValue || filter.Is4K.HasValue)
{
- const int Threshold = 1200;
- if (filter.IsHD.Value)
- {
- minWidth = Threshold;
- }
- else
+ bool includeSD = false;
+ bool includeHD = false;
+ bool include4K = false;
+
+ if (filter.IsHD.HasValue && !filter.IsHD.Value)
{
- maxWidth = Threshold - 1;
+ includeSD = true;
}
- }
- if (filter.Is4K.HasValue)
- {
- const int Threshold = 3800;
- if (filter.Is4K.Value)
+ if (filter.IsHD.HasValue && filter.IsHD.Value)
{
- minWidth = Threshold;
+ includeHD = true;
}
- else
+
+ if (filter.Is4K.HasValue && filter.Is4K.Value)
{
- maxWidth = Threshold - 1;
+ include4K = true;
}
+
+ baseQuery = baseQuery.Where(e =>
+ (includeSD && e.Width < HDWidth) ||
+ (includeHD && e.Width >= HDWidth && !(e.Width >= UHDWidth || e.Height >= UHDHeight)) ||
+ (include4K && (e.Width >= UHDWidth || e.Height >= UHDHeight)));
}
if (minWidth.HasValue)
@@ -1346,7 +1478,7 @@ public sealed class BaseItemRepository
if (maxWidth.HasValue)
{
- baseQuery = baseQuery.Where(e => e.Width >= maxWidth);
+ baseQuery = baseQuery.Where(e => e.Width <= maxWidth);
}
if (filter.MaxHeight.HasValue)
@@ -1429,6 +1561,7 @@ public sealed class BaseItemRepository
}
var includeTypes = filter.IncludeItemTypes;
+
// Only specify excluded types if no included types are specified
if (filter.IncludeItemTypes.Length == 0)
{
@@ -1454,25 +1587,10 @@ public sealed class BaseItemRepository
baseQuery = baseQuery.Where(e => !excludeTypeName.Contains(e.Type));
}
}
- else if (includeTypes.Length == 1)
- {
- if (_itemTypeLookup.BaseItemKindNames.TryGetValue(includeTypes[0], out var includeTypeName))
- {
- baseQuery = baseQuery.Where(e => e.Type == includeTypeName);
- }
- }
- else if (includeTypes.Length > 1)
+ else
{
- var includeTypeName = new List<string>();
- foreach (var includeType in includeTypes)
- {
- if (_itemTypeLookup.BaseItemKindNames.TryGetValue(includeType, out var baseItemKindName))
- {
- includeTypeName.Add(baseItemKindName!);
- }
- }
-
- baseQuery = baseQuery.Where(e => includeTypeName.Contains(e.Type));
+ string[] types = includeTypes.Select(f => _itemTypeLookup.BaseItemKindNames.GetValueOrDefault(f)).Where(e => e != null).ToArray()!;
+ baseQuery = baseQuery.WhereOneOrMany(types, f => f.Type);
}
if (filter.ChannelIds.Count > 0)
@@ -1578,7 +1696,7 @@ public sealed class BaseItemRepository
if (filter.MinPremiereDate.HasValue)
{
- baseQuery = baseQuery.Where(e => e.PremiereDate <= filter.MinPremiereDate.Value);
+ baseQuery = baseQuery.Where(e => e.PremiereDate >= filter.MinPremiereDate.Value);
}
if (filter.MaxPremiereDate.HasValue)
@@ -1730,64 +1848,59 @@ public sealed class BaseItemRepository
if (filter.ArtistIds.Length > 0)
{
- baseQuery = baseQuery
- .Where(e => e.ItemValues!.Any(f => f.ItemValue.Type <= ItemValueType.Artist && filter.ArtistIds.Contains(f.ItemId)));
+ baseQuery = baseQuery.WhereReferencedItem(context, ItemValueType.Artist, filter.ArtistIds);
}
if (filter.AlbumArtistIds.Length > 0)
{
- baseQuery = baseQuery
- .Where(e => e.ItemValues!.Any(f => f.ItemValue.Type == ItemValueType.Artist && filter.AlbumArtistIds.Contains(f.ItemId)));
+ baseQuery = baseQuery.WhereReferencedItem(context, ItemValueType.Artist, filter.AlbumArtistIds);
}
if (filter.ContributingArtistIds.Length > 0)
{
- baseQuery = baseQuery
- .Where(e => e.ItemValues!.Any(f => f.ItemValue.Type == ItemValueType.Artist && filter.ContributingArtistIds.Contains(f.ItemId)));
+ baseQuery = baseQuery.WhereReferencedItem(context, ItemValueType.Artist, filter.ContributingArtistIds);
}
if (filter.AlbumIds.Length > 0)
{
- baseQuery = baseQuery.Where(e => context.BaseItems.Where(f => filter.AlbumIds.Contains(f.Id)).Any(f => f.Name == e.Album));
+ var subQuery = context.BaseItems.WhereOneOrMany(filter.AlbumIds, f => f.Id);
+ baseQuery = baseQuery.Where(e => subQuery.Any(f => f.Name == e.Album));
}
if (filter.ExcludeArtistIds.Length > 0)
{
- baseQuery = baseQuery
- .Where(e => !e.ItemValues!.Any(f => f.ItemValue.Type == ItemValueType.Artist && filter.ExcludeArtistIds.Contains(f.ItemId)));
+ baseQuery = baseQuery.WhereReferencedItem(context, ItemValueType.Artist, filter.ExcludeArtistIds, true);
}
if (filter.GenreIds.Count > 0)
{
- baseQuery = baseQuery
- .Where(e => e.ItemValues!.Any(f => f.ItemValue.Type == ItemValueType.Genre && filter.GenreIds.Contains(f.ItemId)));
+ baseQuery = baseQuery.WhereReferencedItem(context, ItemValueType.Genre, filter.GenreIds.ToArray());
}
if (filter.Genres.Count > 0)
{
- var cleanGenres = filter.Genres.Select(e => GetCleanValue(e)).ToArray();
+ var cleanGenres = filter.Genres.Select(e => GetCleanValue(e)).ToArray().OneOrManyExpressionBuilder<ItemValueMap, string>(f => f.ItemValue.CleanValue);
baseQuery = baseQuery
- .Where(e => e.ItemValues!.Any(f => f.ItemValue.Type == ItemValueType.Genre && cleanGenres.Contains(f.ItemValue.CleanValue)));
+ .Where(e => e.ItemValues!.AsQueryable().Where(f => f.ItemValue.Type == ItemValueType.Genre).Any(cleanGenres));
}
if (tags.Count > 0)
{
- var cleanValues = tags.Select(e => GetCleanValue(e)).ToArray();
+ var cleanValues = tags.Select(e => GetCleanValue(e)).ToArray().OneOrManyExpressionBuilder<ItemValueMap, string>(f => f.ItemValue.CleanValue);
baseQuery = baseQuery
- .Where(e => e.ItemValues!.Any(f => f.ItemValue.Type == ItemValueType.Tags && cleanValues.Contains(f.ItemValue.CleanValue)));
+ .Where(e => e.ItemValues!.AsQueryable().Where(f => f.ItemValue.Type == ItemValueType.Tags).Any(cleanValues));
}
if (excludeTags.Count > 0)
{
- var cleanValues = excludeTags.Select(e => GetCleanValue(e)).ToArray();
+ var cleanValues = excludeTags.Select(e => GetCleanValue(e)).ToArray().OneOrManyExpressionBuilder<ItemValueMap, string>(f => f.ItemValue.CleanValue);
baseQuery = baseQuery
- .Where(e => !e.ItemValues!.Any(f => f.ItemValue.Type == ItemValueType.Tags && cleanValues.Contains(f.ItemValue.CleanValue)));
+ .Where(e => !e.ItemValues!.AsQueryable().Where(f => f.ItemValue.Type == ItemValueType.Tags).Any(cleanValues));
}
if (filter.StudioIds.Length > 0)
{
- baseQuery = baseQuery
- .Where(e => e.ItemValues!.Any(f => f.ItemValue.Type == ItemValueType.Studios && filter.StudioIds.Contains(f.ItemId)));
+ baseQuery = baseQuery.WhereReferencedItem(context, ItemValueType.Studios, filter.StudioIds.ToArray());
}
if (filter.OfficialRatings.Length > 0)
@@ -1796,61 +1909,73 @@ public sealed class BaseItemRepository
.Where(e => filter.OfficialRatings.Contains(e.OfficialRating));
}
- if (filter.HasParentalRating ?? false)
+ Expression<Func<BaseItemEntity, bool>>? minParentalRatingFilter = null;
+ if (filter.MinParentalRating != null)
{
- if (filter.MinParentalRating.HasValue)
+ var min = filter.MinParentalRating;
+ minParentalRatingFilter = e => e.InheritedParentalRatingValue >= min.Score || e.InheritedParentalRatingValue == null;
+ if (min.SubScore != null)
{
- baseQuery = baseQuery
- .Where(e => e.InheritedParentalRatingValue >= filter.MinParentalRating.Value);
+ minParentalRatingFilter = minParentalRatingFilter.And(e => e.InheritedParentalRatingValue >= min.SubScore || e.InheritedParentalRatingValue == null);
}
+ }
- if (filter.MaxParentalRating.HasValue)
+ Expression<Func<BaseItemEntity, bool>>? maxParentalRatingFilter = null;
+ if (filter.MaxParentalRating != null)
+ {
+ var max = filter.MaxParentalRating;
+ maxParentalRatingFilter = e => e.InheritedParentalRatingValue <= max.Score || e.InheritedParentalRatingValue == null;
+ if (max.SubScore != null)
{
- baseQuery = baseQuery
- .Where(e => e.InheritedParentalRatingValue < filter.MaxParentalRating.Value);
+ maxParentalRatingFilter = maxParentalRatingFilter.And(e => e.InheritedParentalRatingValue <= max.SubScore || e.InheritedParentalRatingValue == null);
}
}
- else if (filter.BlockUnratedItems.Length > 0)
+
+ if (filter.HasParentalRating ?? false)
{
- var unratedItems = filter.BlockUnratedItems.Select(f => f.ToString()).ToArray();
- if (filter.MinParentalRating.HasValue)
+ if (minParentalRatingFilter != null)
{
- if (filter.MaxParentalRating.HasValue)
- {
- baseQuery = baseQuery
- .Where(e => (e.InheritedParentalRatingValue == null && !unratedItems.Contains(e.UnratedType))
- || (e.InheritedParentalRatingValue >= filter.MinParentalRating && e.InheritedParentalRatingValue <= filter.MaxParentalRating));
- }
- else
- {
- baseQuery = baseQuery
- .Where(e => (e.InheritedParentalRatingValue == null && !unratedItems.Contains(e.UnratedType))
- || e.InheritedParentalRatingValue >= filter.MinParentalRating);
- }
+ baseQuery = baseQuery.Where(minParentalRatingFilter);
}
- else
+
+ if (maxParentalRatingFilter != null)
{
- baseQuery = baseQuery
- .Where(e => e.InheritedParentalRatingValue != null && !unratedItems.Contains(e.UnratedType));
+ baseQuery = baseQuery.Where(maxParentalRatingFilter);
}
}
- else if (filter.MinParentalRating.HasValue)
+ else if (filter.BlockUnratedItems.Length > 0)
{
- if (filter.MaxParentalRating.HasValue)
+ var unratedItemTypes = filter.BlockUnratedItems.Select(f => f.ToString()).ToArray();
+ Expression<Func<BaseItemEntity, bool>> unratedItemFilter = e => e.InheritedParentalRatingValue != null || !unratedItemTypes.Contains(e.UnratedType);
+
+ if (minParentalRatingFilter != null && maxParentalRatingFilter != null)
{
- baseQuery = baseQuery
- .Where(e => e.InheritedParentalRatingValue != null && e.InheritedParentalRatingValue >= filter.MinParentalRating.Value && e.InheritedParentalRatingValue <= filter.MaxParentalRating.Value);
+ baseQuery = baseQuery.Where(unratedItemFilter.And(minParentalRatingFilter.And(maxParentalRatingFilter)));
+ }
+ else if (minParentalRatingFilter != null)
+ {
+ baseQuery = baseQuery.Where(unratedItemFilter.And(minParentalRatingFilter));
+ }
+ else if (maxParentalRatingFilter != null)
+ {
+ baseQuery = baseQuery.Where(unratedItemFilter.And(maxParentalRatingFilter));
}
else
{
- baseQuery = baseQuery
- .Where(e => e.InheritedParentalRatingValue != null && e.InheritedParentalRatingValue >= filter.MinParentalRating.Value);
+ baseQuery = baseQuery.Where(unratedItemFilter);
}
}
- else if (filter.MaxParentalRating.HasValue)
+ else if (minParentalRatingFilter != null || maxParentalRatingFilter != null)
{
- baseQuery = baseQuery
- .Where(e => e.InheritedParentalRatingValue != null && e.InheritedParentalRatingValue >= filter.MaxParentalRating.Value);
+ if (minParentalRatingFilter != null)
+ {
+ baseQuery = baseQuery.Where(minParentalRatingFilter);
+ }
+
+ if (maxParentalRatingFilter != null)
+ {
+ baseQuery = baseQuery.Where(maxParentalRatingFilter);
+ }
}
else if (!filter.HasParentalRating ?? false)
{
@@ -1945,30 +2070,30 @@ public sealed class BaseItemRepository
if (filter.IsDeadArtist.HasValue && filter.IsDeadArtist.Value)
{
baseQuery = baseQuery
- .Where(e => e.ItemValues!.Count(f => f.ItemValue.Type == ItemValueType.Artist || f.ItemValue.Type == ItemValueType.AlbumArtist) == 1);
+ .Where(e => !context.ItemValues.Where(f => _getAllArtistsValueTypes.Contains(f.Type)).Any(f => f.Value == e.Name));
}
if (filter.IsDeadStudio.HasValue && filter.IsDeadStudio.Value)
{
baseQuery = baseQuery
- .Where(e => e.ItemValues!.Count(f => f.ItemValue.Type == ItemValueType.Studios) == 1);
+ .Where(e => !context.ItemValues.Where(f => _getStudiosValueTypes.Contains(f.Type)).Any(f => f.Value == e.Name));
}
- if (filter.IsDeadPerson.HasValue && filter.IsDeadPerson.Value)
+ if (filter.IsDeadGenre.HasValue && filter.IsDeadGenre.Value)
{
baseQuery = baseQuery
- .Where(e => !context.Peoples.Any(f => f.Name == e.Name));
+ .Where(e => !context.ItemValues.Where(f => _getGenreValueTypes.Contains(f.Type)).Any(f => f.Value == e.Name));
}
- if (filter.Years.Length == 1)
+ if (filter.IsDeadPerson.HasValue && filter.IsDeadPerson.Value)
{
baseQuery = baseQuery
- .Where(e => e.ProductionYear == filter.Years[0]);
+ .Where(e => !context.Peoples.Any(f => f.Name == e.Name));
}
- else if (filter.Years.Length > 1)
+
+ if (filter.Years.Length > 0)
{
- baseQuery = baseQuery
- .Where(e => filter.Years.Any(f => f == e.ProductionYear));
+ baseQuery = baseQuery.WhereOneOrMany(filter.Years, e => e.ProductionYear!.Value);
}
var isVirtualItem = filter.IsVirtualItem ?? filter.IsMissing;
@@ -2009,14 +2134,12 @@ public sealed class BaseItemRepository
if (filter.MediaTypes.Length > 0)
{
var mediaTypes = filter.MediaTypes.Select(f => f.ToString()).ToArray();
- baseQuery = baseQuery
- .Where(e => mediaTypes.Contains(e.MediaType));
+ baseQuery = baseQuery.WhereOneOrMany(mediaTypes, e => e.MediaType);
}
if (filter.ItemIds.Length > 0)
{
- baseQuery = baseQuery
- .Where(e => filter.ItemIds.Contains(e.Id));
+ baseQuery = baseQuery.WhereOneOrMany(filter.ItemIds, e => e.Id);
}
if (filter.ExcludeItemIds.Length > 0)
@@ -2062,19 +2185,19 @@ public sealed class BaseItemRepository
}
else
{
- baseQuery = baseQuery.Where(e => queryTopParentIds.Contains(e.TopParentId!.Value));
+ baseQuery = baseQuery.WhereOneOrMany(queryTopParentIds, e => e.TopParentId!.Value);
}
}
if (filter.AncestorIds.Length > 0)
{
- baseQuery = baseQuery.Where(e => e.Children!.Any(f => filter.AncestorIds.Contains(f.ParentItemId)));
+ baseQuery = baseQuery.Where(e => e.Parents!.Any(f => filter.AncestorIds.Contains(f.ParentItemId)));
}
if (!string.IsNullOrWhiteSpace(filter.AncestorWithPresentationUniqueKey))
{
baseQuery = baseQuery
- .Where(e => context.BaseItems.Where(f => f.PresentationUniqueKey == filter.AncestorWithPresentationUniqueKey).Any(f => f.ParentAncestors!.Any(w => w.ItemId == f.Id)));
+ .Where(e => context.BaseItems.Where(f => f.PresentationUniqueKey == filter.AncestorWithPresentationUniqueKey).Any(f => f.Children!.Any(w => w.ItemId == e.Id)));
}
if (!string.IsNullOrWhiteSpace(filter.SeriesPresentationUniqueKey))
@@ -2109,7 +2232,7 @@ public sealed class BaseItemRepository
{
baseQuery = baseQuery
.Where(e =>
- e.ParentAncestors!
+ e.Parents!
.Any(f =>
f.ParentItem.ItemValues!.Any(w => w.ItemValue.Type == ItemValueType.Tags && filter.IncludeInheritedTags.Contains(w.ItemValue.CleanValue))
|| e.Data!.Contains($"OwnerUserId\":\"{filter.User!.Id:N}\"")));
@@ -2118,7 +2241,7 @@ public sealed class BaseItemRepository
else
{
baseQuery = baseQuery
- .Where(e => e.ParentAncestors!.Any(f => f.ParentItem.ItemValues!.Any(w => w.ItemValue.Type == ItemValueType.Tags && filter.IncludeInheritedTags.Contains(w.ItemValue.CleanValue))));
+ .Where(e => e.Parents!.Any(f => f.ParentItem.ItemValues!.Any(w => w.ItemValue.Type == ItemValueType.Tags && filter.IncludeInheritedTags.Contains(w.ItemValue.CleanValue))));
}
}
diff --git a/Jellyfin.Server.Implementations/Item/ChapterRepository.cs b/Jellyfin.Server.Implementations/Item/ChapterRepository.cs
index 93e15735c..e0d23a261 100644
--- a/Jellyfin.Server.Implementations/Item/ChapterRepository.cs
+++ b/Jellyfin.Server.Implementations/Item/ChapterRepository.cs
@@ -1,12 +1,10 @@
using System;
using System.Collections.Generic;
-using System.Collections.Immutable;
using System.Linq;
using Jellyfin.Database.Implementations;
using Jellyfin.Database.Implementations.Entities;
-using MediaBrowser.Controller.Chapters;
using MediaBrowser.Controller.Drawing;
-using MediaBrowser.Model.Dto;
+using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.Entities;
using Microsoft.EntityFrameworkCore;
@@ -31,19 +29,7 @@ public class ChapterRepository : IChapterRepository
_imageProcessor = imageProcessor;
}
- /// <inheritdoc cref="IChapterRepository"/>
- public ChapterInfo? GetChapter(BaseItemDto baseItem, int index)
- {
- return GetChapter(baseItem.Id, index);
- }
-
- /// <inheritdoc cref="IChapterRepository"/>
- public IReadOnlyList<ChapterInfo> GetChapters(BaseItemDto baseItem)
- {
- return GetChapters(baseItem.Id);
- }
-
- /// <inheritdoc cref="IChapterRepository"/>
+ /// <inheritdoc />
public ChapterInfo? GetChapter(Guid baseItemId, int index)
{
using var context = _dbProvider.CreateDbContext();
@@ -62,7 +48,7 @@ public class ChapterRepository : IChapterRepository
return null;
}
- /// <inheritdoc cref="IChapterRepository"/>
+ /// <inheritdoc />
public IReadOnlyList<ChapterInfo> GetChapters(Guid baseItemId)
{
using var context = _dbProvider.CreateDbContext();
@@ -77,7 +63,7 @@ public class ChapterRepository : IChapterRepository
.ToArray();
}
- /// <inheritdoc cref="IChapterRepository"/>
+ /// <inheritdoc />
public void SaveChapters(Guid itemId, IReadOnlyList<ChapterInfo> chapters)
{
using var context = _dbProvider.CreateDbContext();
@@ -95,6 +81,14 @@ public class ChapterRepository : IChapterRepository
}
}
+ /// <inheritdoc />
+ public void DeleteChapters(Guid itemId)
+ {
+ using var context = _dbProvider.CreateDbContext();
+ context.Chapters.Where(c => c.ItemId.Equals(itemId)).ExecuteDelete();
+ context.SaveChanges();
+ }
+
private Chapter Map(ChapterInfo chapterInfo, int index, Guid itemId)
{
return new Chapter()
@@ -118,7 +112,12 @@ public class ChapterRepository : IChapterRepository
ImagePath = chapterInfo.ImagePath,
Name = chapterInfo.Name,
};
- chapterEntity.ImageTag = _imageProcessor.GetImageCacheTag(baseItemPath, chapterEntity.ImageDateModified);
+
+ if (!string.IsNullOrEmpty(chapterInfo.ImagePath))
+ {
+ chapterEntity.ImageTag = _imageProcessor.GetImageCacheTag(baseItemPath, chapterEntity.ImageDateModified);
+ }
+
return chapterEntity;
}
}
diff --git a/Jellyfin.Server.Implementations/Item/KeyframeRepository.cs b/Jellyfin.Server.Implementations/Item/KeyframeRepository.cs
new file mode 100644
index 000000000..93c6f472e
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Item/KeyframeRepository.cs
@@ -0,0 +1,72 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Database.Implementations;
+using Jellyfin.Database.Implementations.Entities;
+using MediaBrowser.Controller.Persistence;
+using Microsoft.EntityFrameworkCore;
+
+namespace Jellyfin.Server.Implementations.Item;
+
+/// <summary>
+/// Repository for obtaining Keyframe data.
+/// </summary>
+public class KeyframeRepository : IKeyframeRepository
+{
+ private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="KeyframeRepository"/> class.
+ /// </summary>
+ /// <param name="dbProvider">The EFCore db factory.</param>
+ public KeyframeRepository(IDbContextFactory<JellyfinDbContext> dbProvider)
+ {
+ _dbProvider = dbProvider;
+ }
+
+ private static MediaEncoding.Keyframes.KeyframeData Map(KeyframeData entity)
+ {
+ return new MediaEncoding.Keyframes.KeyframeData(
+ entity.TotalDuration,
+ (entity.KeyframeTicks ?? []).ToList());
+ }
+
+ private KeyframeData Map(MediaEncoding.Keyframes.KeyframeData dto, Guid itemId)
+ {
+ return new()
+ {
+ ItemId = itemId,
+ TotalDuration = dto.TotalDuration,
+ KeyframeTicks = dto.KeyframeTicks.ToList()
+ };
+ }
+
+ /// <inheritdoc />
+ public IReadOnlyList<MediaEncoding.Keyframes.KeyframeData> GetKeyframeData(Guid itemId)
+ {
+ using var context = _dbProvider.CreateDbContext();
+
+ return context.KeyframeData.AsNoTracking().Where(e => e.ItemId.Equals(itemId)).Select(e => Map(e)).ToList();
+ }
+
+ /// <inheritdoc />
+ public async Task SaveKeyframeDataAsync(Guid itemId, MediaEncoding.Keyframes.KeyframeData data, CancellationToken cancellationToken)
+ {
+ using var context = _dbProvider.CreateDbContext();
+ using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
+ await context.KeyframeData.Where(e => e.ItemId.Equals(itemId)).ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
+ await context.KeyframeData.AddAsync(Map(data, itemId), cancellationToken).ConfigureAwait(false);
+ await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+ await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ /// <inheritdoc />
+ public async Task DeleteKeyframeDataAsync(Guid itemId, CancellationToken cancellationToken)
+ {
+ using var context = _dbProvider.CreateDbContext();
+ await context.KeyframeData.Where(e => e.ItemId.Equals(itemId)).ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
+ await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Item/MediaStreamRepository.cs b/Jellyfin.Server.Implementations/Item/MediaStreamRepository.cs
index 36c3b9e56..7eb13b740 100644
--- a/Jellyfin.Server.Implementations/Item/MediaStreamRepository.cs
+++ b/Jellyfin.Server.Implementations/Item/MediaStreamRepository.cs
@@ -100,7 +100,18 @@ public class MediaStreamRepository : IMediaStreamRepository
dto.IsAVC = entity.IsAvc;
dto.Codec = entity.Codec;
- dto.Language = entity.Language;
+
+ var language = entity.Language;
+
+ // Check if the language has multiple three letter ISO codes
+ // if yes choose the first as that is the ISO 639-2/T code we're needing
+ if (language != null && _localization.TryGetISO6392TFromB(language, out string? isoT))
+ {
+ language = isoT;
+ }
+
+ dto.Language = language;
+
dto.ChannelLayout = entity.ChannelLayout;
dto.Profile = entity.Profile;
dto.AspectRatio = entity.AspectRatio;
@@ -140,6 +151,7 @@ public class MediaStreamRepository : IMediaStreamRepository
dto.DvBlSignalCompatibilityId = entity.DvBlSignalCompatibilityId;
dto.IsHearingImpaired = entity.IsHearingImpaired.GetValueOrDefault();
dto.Rotation = entity.Rotation;
+ dto.Hdr10PlusPresentFlag = entity.Hdr10PlusPresentFlag;
if (dto.Type is MediaStreamType.Audio or MediaStreamType.Subtitle)
{
@@ -207,7 +219,8 @@ public class MediaStreamRepository : IMediaStreamRepository
BlPresentFlag = dto.BlPresentFlag,
DvBlSignalCompatibilityId = dto.DvBlSignalCompatibilityId,
IsHearingImpaired = dto.IsHearingImpaired,
- Rotation = dto.Rotation
+ Rotation = dto.Rotation,
+ Hdr10PlusPresentFlag = dto.Hdr10PlusPresentFlag,
};
return entity;
}
diff --git a/Jellyfin.Server.Implementations/Item/OrderMapper.cs b/Jellyfin.Server.Implementations/Item/OrderMapper.cs
index 03249b927..a0c127031 100644
--- a/Jellyfin.Server.Implementations/Item/OrderMapper.cs
+++ b/Jellyfin.Server.Implementations/Item/OrderMapper.cs
@@ -44,7 +44,7 @@ public static class OrderMapper
ItemSortBy.DateCreated => e => e.DateCreated,
ItemSortBy.PremiereDate => e => (e.PremiereDate ?? (e.ProductionYear.HasValue ? DateTime.MinValue.AddYears(e.ProductionYear.Value - 1) : null)),
ItemSortBy.StartDate => e => e.StartDate,
- ItemSortBy.Name => e => e.Name,
+ ItemSortBy.Name => e => e.CleanName,
ItemSortBy.CommunityRating => e => e.CommunityRating,
ItemSortBy.ProductionYear => e => e.ProductionYear,
ItemSortBy.CriticRating => e => e.CriticRating,
diff --git a/Jellyfin.Server.Implementations/Item/PeopleRepository.cs b/Jellyfin.Server.Implementations/Item/PeopleRepository.cs
index 77877835e..be58e2a52 100644
--- a/Jellyfin.Server.Implementations/Item/PeopleRepository.cs
+++ b/Jellyfin.Server.Implementations/Item/PeopleRepository.cs
@@ -5,6 +5,7 @@ using System.Linq;
using Jellyfin.Data.Enums;
using Jellyfin.Database.Implementations;
using Jellyfin.Database.Implementations.Entities;
+using Jellyfin.Database.Implementations.Entities.Libraries;
using Jellyfin.Extensions;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Persistence;
@@ -53,7 +54,7 @@ public class PeopleRepository(IDbContextFactory<JellyfinDbContext> dbProvider, I
public IReadOnlyList<string> GetPeopleNames(InternalPeopleQuery filter)
{
using var context = _dbProvider.CreateDbContext();
- var dbQuery = TranslateQuery(context.Peoples.AsNoTracking(), context, filter);
+ var dbQuery = TranslateQuery(context.Peoples.AsNoTracking(), context, filter).Select(e => e.Name).Distinct();
// dbQuery = dbQuery.OrderBy(e => e.ListOrder);
if (filter.Limit > 0)
@@ -61,41 +62,48 @@ public class PeopleRepository(IDbContextFactory<JellyfinDbContext> dbProvider, I
dbQuery = dbQuery.Take(filter.Limit);
}
- return dbQuery.Select(e => e.Name).ToArray();
+ return dbQuery.ToArray();
}
/// <inheritdoc />
public void UpdatePeople(Guid itemId, IReadOnlyList<PersonInfo> people)
{
using var context = _dbProvider.CreateDbContext();
- using var transaction = context.Database.BeginTransaction();
- context.PeopleBaseItemMap.Where(e => e.ItemId == itemId).ExecuteDelete();
// TODO: yes for __SOME__ reason there can be duplicates.
- foreach (var item in people.DistinctBy(e => e.Id))
+ people = people.DistinctBy(e => e.Id).ToArray();
+ var personids = people.Select(f => f.Id);
+ var existingPersons = context.Peoples.Where(p => personids.Contains(p.Id)).Select(f => f.Id).ToArray();
+ context.Peoples.AddRange(people.Where(e => !existingPersons.Contains(e.Id)).Select(Map));
+ context.SaveChanges();
+
+ var maps = context.PeopleBaseItemMap.Where(e => e.ItemId == itemId).ToList();
+ foreach (var person in people)
{
- var personEntity = Map(item);
- var existingEntity = context.Peoples.FirstOrDefault(e => e.Id == personEntity.Id);
- if (existingEntity is null)
+ var existingMap = maps.FirstOrDefault(e => e.PeopleId == person.Id);
+ if (existingMap is null)
{
- context.Peoples.Add(personEntity);
- existingEntity = personEntity;
+ context.PeopleBaseItemMap.Add(new PeopleBaseItemMap()
+ {
+ Item = null!,
+ ItemId = itemId,
+ People = null!,
+ PeopleId = person.Id,
+ ListOrder = person.SortOrder,
+ SortOrder = person.SortOrder,
+ Role = person.Role
+ });
}
-
- context.PeopleBaseItemMap.Add(new PeopleBaseItemMap()
+ else
{
- Item = null!,
- ItemId = itemId,
- People = existingEntity,
- PeopleId = existingEntity.Id,
- ListOrder = item.SortOrder,
- SortOrder = item.SortOrder,
- Role = item.Role
- });
+ // person mapping already exists so remove from list
+ maps.Remove(existingMap);
+ }
}
+ context.PeopleBaseItemMap.RemoveRange(maps);
+
context.SaveChanges();
- transaction.Commit();
}
private PersonInfo Map(People people)
@@ -133,9 +141,13 @@ public class PeopleRepository(IDbContextFactory<JellyfinDbContext> dbProvider, I
if (filter.User is not null && filter.IsFavorite.HasValue)
{
var personType = itemTypeLookup.BaseItemKindNames[BaseItemKind.Person];
- query = query.Where(e => e.PersonType == personType)
- .Where(e => context.BaseItems.Where(d => d.UserData!.Any(w => w.IsFavorite == filter.IsFavorite && w.UserId.Equals(filter.User.Id)))
- .Select(f => f.Name).Contains(e.Name));
+ var oldQuery = query;
+
+ query = context.UserData
+ .Where(u => u.Item!.Type == personType && u.IsFavorite == filter.IsFavorite && u.UserId.Equals(filter.User.Id))
+ .Join(oldQuery, e => e.Item!.Name, e => e.Name, (item, person) => person)
+ .Distinct()
+ .AsNoTracking();
}
if (!filter.ItemId.IsEmpty())
diff --git a/Jellyfin.Server.Implementations/MediaSegments/MediaSegmentManager.cs b/Jellyfin.Server.Implementations/MediaSegments/MediaSegmentManager.cs
index d6eeafacc..28b6890b0 100644
--- a/Jellyfin.Server.Implementations/MediaSegments/MediaSegmentManager.cs
+++ b/Jellyfin.Server.Implementations/MediaSegments/MediaSegmentManager.cs
@@ -10,12 +10,12 @@ using Jellyfin.Database.Implementations.Entities;
using Jellyfin.Database.Implementations.Enums;
using Jellyfin.Extensions;
using MediaBrowser.Common.Extensions;
-using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaSegments;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model;
+using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.MediaSegments;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
@@ -30,7 +30,6 @@ public class MediaSegmentManager : IMediaSegmentManager
private readonly ILogger<MediaSegmentManager> _logger;
private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
private readonly IMediaSegmentProvider[] _segmentProviders;
- private readonly ILibraryManager _libraryManager;
/// <summary>
/// Initializes a new instance of the <see cref="MediaSegmentManager"/> class.
@@ -38,12 +37,10 @@ public class MediaSegmentManager : IMediaSegmentManager
/// <param name="logger">Logger.</param>
/// <param name="dbProvider">EFCore Database factory.</param>
/// <param name="segmentProviders">List of all media segment providers.</param>
- /// <param name="libraryManager">Library manager.</param>
public MediaSegmentManager(
ILogger<MediaSegmentManager> logger,
IDbContextFactory<JellyfinDbContext> dbProvider,
- IEnumerable<IMediaSegmentProvider> segmentProviders,
- ILibraryManager libraryManager)
+ IEnumerable<IMediaSegmentProvider> segmentProviders)
{
_logger = logger;
_dbProvider = dbProvider;
@@ -51,13 +48,11 @@ public class MediaSegmentManager : IMediaSegmentManager
_segmentProviders = segmentProviders
.OrderBy(i => i is IHasOrder hasOrder ? hasOrder.Order : 0)
.ToArray();
- _libraryManager = libraryManager;
}
/// <inheritdoc/>
- public async Task RunSegmentPluginProviders(BaseItem baseItem, bool overwrite, CancellationToken cancellationToken)
+ public async Task RunSegmentPluginProviders(BaseItem baseItem, LibraryOptions libraryOptions, bool overwrite, CancellationToken cancellationToken)
{
- var libraryOptions = _libraryManager.GetLibraryOptions(baseItem);
var providers = _segmentProviders
.Where(e => !libraryOptions.DisabledMediaSegmentProviders.Contains(GetProviderId(e.Name)))
.OrderBy(i =>
@@ -140,22 +135,21 @@ public class MediaSegmentManager : IMediaSegmentManager
}
/// <inheritdoc />
- public async Task<IEnumerable<MediaSegmentDto>> GetSegmentsAsync(Guid itemId, IEnumerable<MediaSegmentType>? typeFilter, bool filterByProvider = true)
+ public async Task DeleteSegmentsAsync(Guid itemId, CancellationToken cancellationToken)
{
- var baseItem = _libraryManager.GetItemById(itemId);
+ using var db = await _dbProvider.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
+ await db.MediaSegments.Where(e => e.ItemId.Equals(itemId)).ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
+ }
- if (baseItem is null)
+ /// <inheritdoc />
+ public async Task<IEnumerable<MediaSegmentDto>> GetSegmentsAsync(BaseItem? item, IEnumerable<MediaSegmentType>? typeFilter, LibraryOptions libraryOptions, bool filterByProvider = true)
+ {
+ if (item is null)
{
_logger.LogError("Tried to request segments for an invalid item");
return [];
}
- return await GetSegmentsAsync(baseItem, typeFilter, filterByProvider).ConfigureAwait(false);
- }
-
- /// <inheritdoc />
- public async Task<IEnumerable<MediaSegmentDto>> GetSegmentsAsync(BaseItem item, IEnumerable<MediaSegmentType>? typeFilter, bool filterByProvider = true)
- {
using var db = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
var query = db.MediaSegments
@@ -168,7 +162,6 @@ public class MediaSegmentManager : IMediaSegmentManager
if (filterByProvider)
{
- var libraryOptions = _libraryManager.GetLibraryOptions(item);
var providerIds = _segmentProviders
.Where(e => !libraryOptions.DisabledMediaSegmentProviders.Contains(GetProviderId(e.Name)))
.Select(f => GetProviderId(f.Name))
diff --git a/Jellyfin.Server.Implementations/StorageHelpers/StorageHelper.cs b/Jellyfin.Server.Implementations/StorageHelpers/StorageHelper.cs
new file mode 100644
index 000000000..b2f54be7e
--- /dev/null
+++ b/Jellyfin.Server.Implementations/StorageHelpers/StorageHelper.cs
@@ -0,0 +1,111 @@
+using System;
+using System.Globalization;
+using System.IO;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Model.System;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Implementations.StorageHelpers;
+
+/// <summary>
+/// Contains methods to help with checking for storage and returning storage data for jellyfin folders.
+/// </summary>
+public static class StorageHelper
+{
+ private const long TwoGigabyte = 2_147_483_647L;
+ private const long FiveHundredAndTwelveMegaByte = 536_870_911L;
+ private static readonly string[] _byteHumanizedSuffixes = ["B", "KB", "MB", "GB", "TB", "PB", "EB"];
+
+ /// <summary>
+ /// Tests the available storage capacity on the jellyfin paths with estimated minimum values.
+ /// </summary>
+ /// <param name="applicationPaths">The application paths.</param>
+ /// <param name="logger">Logger.</param>
+ public static void TestCommonPathsForStorageCapacity(IApplicationPaths applicationPaths, ILogger logger)
+ {
+ TestDataDirectorySize(applicationPaths.DataPath, logger, TwoGigabyte);
+ TestDataDirectorySize(applicationPaths.LogDirectoryPath, logger, FiveHundredAndTwelveMegaByte);
+ TestDataDirectorySize(applicationPaths.CachePath, logger, TwoGigabyte);
+ TestDataDirectorySize(applicationPaths.ProgramDataPath, logger, TwoGigabyte);
+ TestDataDirectorySize(applicationPaths.TempDirectory, logger, TwoGigabyte);
+ }
+
+ /// <summary>
+ /// Gets the free space of a specific directory.
+ /// </summary>
+ /// <param name="path">Path to a folder.</param>
+ /// <returns>The number of bytes available space.</returns>
+ public static FolderStorageInfo GetFreeSpaceOf(string path)
+ {
+ try
+ {
+ var driveInfo = new DriveInfo(path);
+ return new FolderStorageInfo()
+ {
+ Path = path,
+ FreeSpace = driveInfo.AvailableFreeSpace,
+ UsedSpace = driveInfo.TotalSize - driveInfo.AvailableFreeSpace,
+ StorageType = driveInfo.DriveType.ToString(),
+ DeviceId = driveInfo.Name,
+ };
+ }
+ catch
+ {
+ return new FolderStorageInfo()
+ {
+ Path = path,
+ FreeSpace = -1,
+ UsedSpace = -1,
+ StorageType = null,
+ DeviceId = null
+ };
+ }
+ }
+
+ /// <summary>
+ /// Gets the underlying drive data from a given path and checks if the available storage capacity matches the threshold.
+ /// </summary>
+ /// <param name="path">The path to a folder to evaluate.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="threshold">The threshold to check for or -1 to just log the data.</param>
+ /// <exception cref="InvalidOperationException">Thrown when the threshold is not available on the underlying storage.</exception>
+ private static void TestDataDirectorySize(string path, ILogger logger, long threshold = -1)
+ {
+ logger.LogDebug("Check path {TestPath} for storage capacity", path);
+ Directory.CreateDirectory(path);
+
+ var drive = new DriveInfo(path);
+ if (threshold != -1 && drive.AvailableFreeSpace < threshold)
+ {
+ throw new InvalidOperationException($"The path `{path}` has insufficient free space. Required: at least {HumanizeStorageSize(threshold)}.");
+ }
+
+ logger.LogInformation(
+ "Storage path `{TestPath}` ({StorageType}) successfully checked with {FreeSpace} free which is over the minimum of {MinFree}.",
+ path,
+ drive.DriveType,
+ HumanizeStorageSize(drive.AvailableFreeSpace),
+ HumanizeStorageSize(threshold));
+ }
+
+ /// <summary>
+ /// Formats a size in bytes into a common human readable form.
+ /// </summary>
+ /// <remarks>
+ /// Taken and slightly modified from https://stackoverflow.com/a/4975942/1786007 .
+ /// </remarks>
+ /// <param name="byteCount">The size in bytes.</param>
+ /// <returns>A human readable approximate representation of the argument.</returns>
+ public static string HumanizeStorageSize(long byteCount)
+ {
+ if (byteCount == 0)
+ {
+ return $"0{_byteHumanizedSuffixes[0]}";
+ }
+
+ var bytes = Math.Abs(byteCount);
+ var place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
+ var num = Math.Round(bytes / Math.Pow(1024, place), 1);
+ return (Math.Sign(byteCount) * num).ToString(CultureInfo.InvariantCulture) + _byteHumanizedSuffixes[place];
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Trickplay/TrickplayManager.cs b/Jellyfin.Server.Implementations/Trickplay/TrickplayManager.cs
index bf39f13a7..6f2d2a107 100644
--- a/Jellyfin.Server.Implementations/Trickplay/TrickplayManager.cs
+++ b/Jellyfin.Server.Implementations/Trickplay/TrickplayManager.cs
@@ -7,6 +7,7 @@ using System.Text;
using System.Threading;
using System.Threading.Tasks;
using AsyncKeyedLock;
+using J2N.Collections.Generic.Extensions;
using Jellyfin.Database.Implementations;
using Jellyfin.Database.Implementations.Entities;
using MediaBrowser.Common.Configuration;
@@ -14,7 +15,6 @@ using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.IO;
-using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Trickplay;
using MediaBrowser.Model.Configuration;
@@ -34,7 +34,6 @@ public class TrickplayManager : ITrickplayManager
private readonly IMediaEncoder _mediaEncoder;
private readonly IFileSystem _fileSystem;
private readonly EncodingHelper _encodingHelper;
- private readonly ILibraryManager _libraryManager;
private readonly IServerConfigurationManager _config;
private readonly IImageEncoder _imageEncoder;
private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
@@ -51,7 +50,6 @@ public class TrickplayManager : ITrickplayManager
/// <param name="mediaEncoder">The media encoder.</param>
/// <param name="fileSystem">The file system.</param>
/// <param name="encodingHelper">The encoding helper.</param>
- /// <param name="libraryManager">The library manager.</param>
/// <param name="config">The server configuration manager.</param>
/// <param name="imageEncoder">The image encoder.</param>
/// <param name="dbProvider">The database provider.</param>
@@ -62,7 +60,6 @@ public class TrickplayManager : ITrickplayManager
IMediaEncoder mediaEncoder,
IFileSystem fileSystem,
EncodingHelper encodingHelper,
- ILibraryManager libraryManager,
IServerConfigurationManager config,
IImageEncoder imageEncoder,
IDbContextFactory<JellyfinDbContext> dbProvider,
@@ -73,7 +70,6 @@ public class TrickplayManager : ITrickplayManager
_mediaEncoder = mediaEncoder;
_fileSystem = fileSystem;
_encodingHelper = encodingHelper;
- _libraryManager = libraryManager;
_config = config;
_imageEncoder = imageEncoder;
_dbProvider = dbProvider;
@@ -82,10 +78,10 @@ public class TrickplayManager : ITrickplayManager
}
/// <inheritdoc />
- public async Task MoveGeneratedTrickplayDataAsync(Video video, LibraryOptions? libraryOptions, CancellationToken cancellationToken)
+ public async Task MoveGeneratedTrickplayDataAsync(Video video, LibraryOptions libraryOptions, CancellationToken cancellationToken)
{
var options = _config.Configuration.TrickplayOptions;
- if (!CanGenerateTrickplay(video, options.Interval))
+ if (libraryOptions is null || !libraryOptions.EnableTrickplayImageExtraction || !CanGenerateTrickplay(video, options.Interval))
{
return;
}
@@ -97,28 +93,28 @@ public class TrickplayManager : ITrickplayManager
var existingResolution = resolution.Key;
var tileWidth = resolution.Value.TileWidth;
var tileHeight = resolution.Value.TileHeight;
- var shouldBeSavedWithMedia = libraryOptions is null ? false : libraryOptions.SaveTrickplayWithMedia;
- var localOutputDir = GetTrickplayDirectory(video, tileWidth, tileHeight, existingResolution, false);
- var mediaOutputDir = GetTrickplayDirectory(video, tileWidth, tileHeight, existingResolution, true);
- if (shouldBeSavedWithMedia && Directory.Exists(localOutputDir))
+ var shouldBeSavedWithMedia = libraryOptions is not null && libraryOptions.SaveTrickplayWithMedia;
+ var localOutputDir = new DirectoryInfo(GetTrickplayDirectory(video, tileWidth, tileHeight, existingResolution, false));
+ var mediaOutputDir = new DirectoryInfo(GetTrickplayDirectory(video, tileWidth, tileHeight, existingResolution, true));
+ if (shouldBeSavedWithMedia && localOutputDir.Exists)
{
- var localDirFiles = Directory.GetFiles(localOutputDir);
- var mediaDirExists = Directory.Exists(mediaOutputDir);
- if (localDirFiles.Length > 0 && ((mediaDirExists && Directory.GetFiles(mediaOutputDir).Length == 0) || !mediaDirExists))
+ var localDirFiles = localOutputDir.EnumerateFiles();
+ var mediaDirExists = mediaOutputDir.Exists;
+ if (localDirFiles.Any() && ((mediaDirExists && mediaOutputDir.EnumerateFiles().Any()) || !mediaDirExists))
{
// Move images from local dir to media dir
- MoveContent(localOutputDir, mediaOutputDir);
+ MoveContent(localOutputDir.FullName, mediaOutputDir.FullName);
_logger.LogInformation("Moved trickplay images for {ItemName} to {Location}", video.Name, mediaOutputDir);
}
}
- else if (!shouldBeSavedWithMedia && Directory.Exists(mediaOutputDir))
+ else if (!shouldBeSavedWithMedia && mediaOutputDir.Exists)
{
- var mediaDirFiles = Directory.GetFiles(mediaOutputDir);
- var localDirExists = Directory.Exists(localOutputDir);
- if (mediaDirFiles.Length > 0 && ((localDirExists && Directory.GetFiles(localOutputDir).Length == 0) || !localDirExists))
+ var mediaDirFiles = mediaOutputDir.EnumerateFiles();
+ var localDirExists = localOutputDir.Exists;
+ if (mediaDirFiles.Any() && ((localDirExists && localOutputDir.EnumerateFiles().Any()) || !localDirExists))
{
// Move images from media dir to local dir
- MoveContent(mediaOutputDir, localOutputDir);
+ MoveContent(mediaOutputDir.FullName, localOutputDir.FullName);
_logger.LogInformation("Moved trickplay images for {ItemName} to {Location}", video.Name, localOutputDir);
}
}
@@ -131,36 +127,98 @@ public class TrickplayManager : ITrickplayManager
var parent = Directory.GetParent(sourceFolder);
if (parent is not null)
{
- var parentContent = Directory.GetDirectories(parent.FullName);
- if (parentContent.Length == 0)
+ var parentContent = parent.EnumerateDirectories();
+ if (!parentContent.Any())
{
- Directory.Delete(parent.FullName);
+ parent.Delete();
}
}
}
/// <inheritdoc />
- public async Task RefreshTrickplayDataAsync(Video video, bool replace, LibraryOptions? libraryOptions, CancellationToken cancellationToken)
+ public async Task RefreshTrickplayDataAsync(Video video, bool replace, LibraryOptions libraryOptions, CancellationToken cancellationToken)
{
- _logger.LogDebug("Trickplay refresh for {ItemId} (replace existing: {Replace})", video.Id, replace);
-
var options = _config.Configuration.TrickplayOptions;
- if (options.Interval < 1000)
+ if (!CanGenerateTrickplay(video, options.Interval) || libraryOptions is null)
{
- _logger.LogWarning("Trickplay image interval {Interval} is too small, reset to the minimum valid value of 1000", options.Interval);
- options.Interval = 1000;
+ return;
}
- foreach (var width in options.WidthResolutions)
+ var dbContext = await _dbProvider.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
+ await using (dbContext.ConfigureAwait(false))
{
- cancellationToken.ThrowIfCancellationRequested();
- await RefreshTrickplayDataInternal(
- video,
- replace,
- width,
- options,
- libraryOptions,
- cancellationToken).ConfigureAwait(false);
+ var saveWithMedia = libraryOptions.SaveTrickplayWithMedia;
+ var trickplayDirectory = _pathManager.GetTrickplayDirectory(video, saveWithMedia);
+ if (!libraryOptions.EnableTrickplayImageExtraction || replace)
+ {
+ // Prune existing data
+ if (Directory.Exists(trickplayDirectory))
+ {
+ try
+ {
+ Directory.Delete(trickplayDirectory, true);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning("Unable to clear trickplay directory: {Directory}: {Exception}", trickplayDirectory, ex);
+ }
+ }
+
+ await dbContext.TrickplayInfos
+ .Where(i => i.ItemId.Equals(video.Id))
+ .ExecuteDeleteAsync(cancellationToken)
+ .ConfigureAwait(false);
+
+ if (!replace)
+ {
+ return;
+ }
+ }
+
+ _logger.LogDebug("Trickplay refresh for {ItemId} (replace existing: {Replace})", video.Id, replace);
+
+ if (options.Interval < 1000)
+ {
+ _logger.LogWarning("Trickplay image interval {Interval} is too small, reset to the minimum valid value of 1000", options.Interval);
+ options.Interval = 1000;
+ }
+
+ foreach (var width in options.WidthResolutions)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ await RefreshTrickplayDataInternal(
+ video,
+ replace,
+ width,
+ options,
+ saveWithMedia,
+ cancellationToken).ConfigureAwait(false);
+ }
+
+ // Cleanup old trickplay files
+ if (Directory.Exists(trickplayDirectory))
+ {
+ var existingFolders = Directory.GetDirectories(trickplayDirectory).ToList();
+ var trickplayInfos = await dbContext.TrickplayInfos
+ .AsNoTracking()
+ .Where(i => i.ItemId.Equals(video.Id))
+ .ToListAsync(cancellationToken)
+ .ConfigureAwait(false);
+ var expectedFolders = trickplayInfos.Select(i => GetTrickplayDirectory(video, i.TileWidth, i.TileHeight, i.Width, saveWithMedia)).ToList();
+ var foldersToRemove = existingFolders.Except(expectedFolders);
+ foreach (var folder in foldersToRemove)
+ {
+ try
+ {
+ _logger.LogWarning("Pruning trickplay files for {Item}", video.Path);
+ Directory.Delete(folder, true);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning("Unable to remove trickplay directory: {Directory}: {Exception}", folder, ex);
+ }
+ }
+ }
}
}
@@ -169,14 +227,9 @@ public class TrickplayManager : ITrickplayManager
bool replace,
int width,
TrickplayOptions options,
- LibraryOptions? libraryOptions,
+ bool saveWithMedia,
CancellationToken cancellationToken)
{
- if (!CanGenerateTrickplay(video, options.Interval))
- {
- return;
- }
-
var imgTempDir = string.Empty;
using (await _resourcePool.LockAsync(cancellationToken).ConfigureAwait(false))
@@ -220,13 +273,12 @@ public class TrickplayManager : ITrickplayManager
var tileWidth = options.TileWidth;
var tileHeight = options.TileHeight;
- var saveWithMedia = libraryOptions is null ? false : libraryOptions.SaveTrickplayWithMedia;
- var outputDir = GetTrickplayDirectory(video, tileWidth, tileHeight, actualWidth, saveWithMedia);
+ var outputDir = new DirectoryInfo(GetTrickplayDirectory(video, tileWidth, tileHeight, actualWidth, saveWithMedia));
// Import existing trickplay tiles
- if (!replace && Directory.Exists(outputDir))
+ if (!replace && outputDir.Exists)
{
- var existingFiles = Directory.GetFiles(outputDir);
+ var existingFiles = outputDir.GetFiles();
if (existingFiles.Length > 0)
{
var hasTrickplayResolution = await HasTrickplayResolutionAsync(video.Id, actualWidth).ConfigureAwait(false);
@@ -251,9 +303,9 @@ public class TrickplayManager : ITrickplayManager
foreach (var tile in existingFiles)
{
- var image = _imageEncoder.GetImageSize(tile);
+ var image = _imageEncoder.GetImageSize(tile.FullName);
localTrickplayInfo.Height = Math.Max(localTrickplayInfo.Height, (int)Math.Ceiling((double)image.Height / localTrickplayInfo.TileHeight));
- var bitrate = (int)Math.Ceiling((decimal)new FileInfo(tile).Length * 8 / localTrickplayInfo.TileWidth / localTrickplayInfo.TileHeight / (localTrickplayInfo.Interval / 1000));
+ var bitrate = (int)Math.Ceiling((decimal)tile.Length * 8 / localTrickplayInfo.TileWidth / localTrickplayInfo.TileHeight / (localTrickplayInfo.Interval / 1000));
localTrickplayInfo.Bandwidth = Math.Max(localTrickplayInfo.Bandwidth, bitrate);
}
@@ -296,7 +348,7 @@ public class TrickplayManager : ITrickplayManager
.ToList();
// Create tiles
- var trickplayInfo = CreateTiles(images, actualWidth, options, outputDir);
+ var trickplayInfo = CreateTiles(images, actualWidth, options, outputDir.FullName);
// Save tiles info
try
@@ -319,7 +371,7 @@ public class TrickplayManager : ITrickplayManager
// Make sure no files stay in metadata folders on failure
// if tiles info wasn't saved.
- Directory.Delete(outputDir, true);
+ outputDir.Delete(true);
}
}
catch (Exception ex)
@@ -435,12 +487,6 @@ public class TrickplayManager : ITrickplayManager
return false;
}
- var libraryOptions = _libraryManager.GetLibraryOptions(video);
- if (libraryOptions is null || !libraryOptions.EnableTrickplayImageExtraction)
- {
- return false;
- }
-
// Can't extract images if there are no video streams
return video.GetMediaStreams().Count > 0;
}
@@ -507,6 +553,13 @@ public class TrickplayManager : ITrickplayManager
}
/// <inheritdoc />
+ public async Task DeleteTrickplayDataAsync(Guid itemId, CancellationToken cancellationToken)
+ {
+ var dbContext = await _dbProvider.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
+ await dbContext.TrickplayInfos.Where(i => i.ItemId.Equals(itemId)).ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ /// <inheritdoc />
public async Task<Dictionary<string, Dictionary<int, TrickplayInfo>>> GetTrickplayManifest(BaseItem item)
{
var trickplayManifest = new Dictionary<string, Dictionary<int, TrickplayInfo>>();
diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs
index 3c39e5503..3dfb14d71 100644
--- a/Jellyfin.Server.Implementations/Users/UserManager.cs
+++ b/Jellyfin.Server.Implementations/Users/UserManager.cs
@@ -342,7 +342,8 @@ namespace Jellyfin.Server.Implementations.Users
},
Policy = new UserPolicy
{
- MaxParentalRating = user.MaxParentalAgeRating,
+ MaxParentalRating = user.MaxParentalRatingScore,
+ MaxParentalSubRating = user.MaxParentalRatingSubScore,
EnableUserPreferenceAccess = user.EnableUserPreferenceAccess,
RemoteClientBitrateLimit = user.RemoteClientBitrateLimit ?? 0,
AuthenticationProviderId = user.AuthenticationProviderId,
@@ -668,7 +669,8 @@ namespace Jellyfin.Server.Implementations.Users
_ => policy.LoginAttemptsBeforeLockout
};
- user.MaxParentalAgeRating = policy.MaxParentalRating;
+ user.MaxParentalRatingScore = policy.MaxParentalRating;
+ user.MaxParentalRatingSubScore = policy.MaxParentalSubRating;
user.EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess;
user.RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit;
user.AuthenticationProviderId = policy.AuthenticationProviderId;
diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs
index 6066893de..a56baba33 100644
--- a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs
+++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs
@@ -69,16 +69,6 @@ namespace Jellyfin.Server.Extensions
}
/// <summary>
- /// Adds LAN based access filtering to the application pipeline.
- /// </summary>
- /// <param name="appBuilder">The application builder.</param>
- /// <returns>The updated application builder.</returns>
- public static IApplicationBuilder UseLanFiltering(this IApplicationBuilder appBuilder)
- {
- return appBuilder.UseMiddleware<LanFilteringMiddleware>();
- }
-
- /// <summary>
/// Enables url decoding before binding to the application pipeline.
/// </summary>
/// <param name="appBuilder">The <see cref="IApplicationBuilder"/>.</param>
diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
index c6c3f21fe..09a4e2ed3 100644
--- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
+++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
@@ -119,15 +119,15 @@ namespace Jellyfin.Server.Extensions
// https://github.com/dotnet/aspnetcore/blob/master/src/Middleware/HttpOverrides/src/ForwardedHeadersMiddleware.cs
// Enable debug logging on Microsoft.AspNetCore.HttpOverrides.ForwardedHeadersMiddleware to help investigate issues.
- options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
-
if (config.KnownProxies.Length == 0)
{
+ options.ForwardedHeaders = ForwardedHeaders.None;
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
}
else
{
+ options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
AddProxyAddresses(config, config.KnownProxies, options);
}
@@ -215,7 +215,7 @@ namespace Jellyfin.Server.Extensions
});
// Add all xml doc files to swagger generator.
- var xmlFiles = Directory.GetFiles(
+ var xmlFiles = Directory.EnumerateFiles(
AppContext.BaseDirectory,
"*.xml",
SearchOption.TopDirectoryOnly);
diff --git a/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs b/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs
index 7695c0d9e..be9cf0f15 100644
--- a/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs
+++ b/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs
@@ -1,10 +1,14 @@
using System;
+using System.Collections.Generic;
using System.IO;
using System.Net;
+using System.Security.Cryptography.X509Certificates;
using Jellyfin.Server.Helpers;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Extensions;
+using MediaBrowser.Model.Net;
using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
@@ -35,56 +39,98 @@ public static class WebHostBuilderExtensions
return builder
.UseKestrel((builderContext, options) =>
{
- var addresses = appHost.NetManager.GetAllBindInterfaces(false);
+ SetupJellyfinWebServer(
+ appHost.NetManager.GetAllBindInterfaces(false),
+ appHost.HttpPort,
+ appHost.ListenWithHttps ? appHost.HttpsPort : null,
+ appHost.Certificate,
+ startupConfig,
+ appPaths,
+ logger,
+ builderContext,
+ options);
+ })
+ .UseStartup(context => new Startup(appHost, context.Configuration));
+ }
- bool flagged = false;
- foreach (var netAdd in addresses)
+ /// <summary>
+ /// Configures a Kestrel type webServer to bind to the specific arguments.
+ /// </summary>
+ /// <param name="addresses">The IP addresses that should be listend to.</param>
+ /// <param name="httpPort">The http port.</param>
+ /// <param name="httpsPort">If set the https port. If set you must also set the certificate.</param>
+ /// <param name="certificate">The certificate used for https port.</param>
+ /// <param name="startupConfig">The startup config.</param>
+ /// <param name="appPaths">The app paths.</param>
+ /// <param name="logger">A logger.</param>
+ /// <param name="builderContext">The kestrel build pipeline context.</param>
+ /// <param name="options">The kestrel server options.</param>
+ /// <exception cref="InvalidOperationException">Will be thrown when a https port is set but no or an invalid certificate is provided.</exception>
+ public static void SetupJellyfinWebServer(
+ IReadOnlyList<IPData> addresses,
+ int httpPort,
+ int? httpsPort,
+ X509Certificate2? certificate,
+ IConfiguration startupConfig,
+ IApplicationPaths appPaths,
+ ILogger logger,
+ WebHostBuilderContext builderContext,
+ KestrelServerOptions options)
+ {
+ bool flagged = false;
+ foreach (var netAdd in addresses)
+ {
+ var address = netAdd.Address;
+ logger.LogInformation("Kestrel is listening on {Address}", address.Equals(IPAddress.IPv6Any) ? "all interfaces" : address);
+ options.Listen(netAdd.Address, httpPort);
+ if (httpsPort.HasValue)
+ {
+ if (builderContext.HostingEnvironment.IsDevelopment())
{
- var address = netAdd.Address;
- logger.LogInformation("Kestrel is listening on {Address}", address.Equals(IPAddress.IPv6Any) ? "all interfaces" : address);
- options.Listen(netAdd.Address, appHost.HttpPort);
- if (appHost.ListenWithHttps)
+ try
{
options.Listen(
address,
- appHost.HttpsPort,
- listenOptions => listenOptions.UseHttps(appHost.Certificate));
+ httpsPort.Value,
+ listenOptions => listenOptions.UseHttps());
}
- else if (builderContext.HostingEnvironment.IsDevelopment())
+ catch (InvalidOperationException)
{
- try
+ if (!flagged)
{
- options.Listen(
- address,
- appHost.HttpsPort,
- listenOptions => listenOptions.UseHttps());
- }
- catch (InvalidOperationException)
- {
- if (!flagged)
- {
- logger.LogWarning("Failed to listen to HTTPS using the ASP.NET Core HTTPS development certificate. Please ensure it has been installed and set as trusted");
- flagged = true;
- }
+ logger.LogWarning("Failed to listen to HTTPS using the ASP.NET Core HTTPS development certificate. Please ensure it has been installed and set as trusted");
+ flagged = true;
}
}
}
-
- // Bind to unix socket (only on unix systems)
- if (startupConfig.UseUnixSocket() && Environment.OSVersion.Platform == PlatformID.Unix)
+ else
{
- var socketPath = StartupHelpers.GetUnixSocketPath(startupConfig, appPaths);
-
- // Workaround for https://github.com/aspnet/AspNetCore/issues/14134
- if (File.Exists(socketPath))
+ if (certificate is null)
{
- File.Delete(socketPath);
+ throw new InvalidOperationException("Cannot run jellyfin with https without setting a valid certificate.");
}
- options.ListenUnixSocket(socketPath);
- logger.LogInformation("Kestrel listening to unix socket {SocketPath}", socketPath);
+ options.Listen(
+ address,
+ httpsPort.Value,
+ listenOptions => listenOptions.UseHttps(certificate));
}
- })
- .UseStartup(context => new Startup(appHost, context.Configuration));
+ }
+ }
+
+ // Bind to unix socket (only on unix systems)
+ if (startupConfig.UseUnixSocket() && Environment.OSVersion.Platform == PlatformID.Unix)
+ {
+ var socketPath = StartupHelpers.GetUnixSocketPath(startupConfig, appPaths);
+
+ // Workaround for https://github.com/aspnet/AspNetCore/issues/14134
+ if (File.Exists(socketPath))
+ {
+ File.Delete(socketPath);
+ }
+
+ options.ListenUnixSocket(socketPath);
+ logger.LogInformation("Kestrel listening to unix socket {SocketPath}", socketPath);
+ }
}
}
diff --git a/Jellyfin.Server/Filters/AdditionalModelFilter.cs b/Jellyfin.Server/Filters/AdditionalModelFilter.cs
index bf38f741c..421eeecda 100644
--- a/Jellyfin.Server/Filters/AdditionalModelFilter.cs
+++ b/Jellyfin.Server/Filters/AdditionalModelFilter.cs
@@ -25,7 +25,7 @@ namespace Jellyfin.Server.Filters
public class AdditionalModelFilter : IDocumentFilter
{
// Array of options that should not be visible in the api spec.
- private static readonly Type[] _ignoredConfigurations = { typeof(MigrationOptions) };
+ private static readonly Type[] _ignoredConfigurations = { typeof(MigrationOptions), typeof(MediaBrowser.Model.Branding.BrandingOptions) };
private readonly IServerConfigurationManager _serverConfigurationManager;
/// <summary>
@@ -92,17 +92,51 @@ namespace Jellyfin.Server.Filters
continue;
}
- // Additional discriminator needed for GroupUpdate models...
- if (messageType == SessionMessageType.SyncPlayGroupUpdate && type != typeof(SyncPlayGroupUpdateCommandMessage))
- {
- continue;
- }
-
var schema = context.SchemaGenerator.GenerateSchema(type, context.SchemaRepository);
outboundWebSocketSchemas.Add(schema);
outboundWebSocketDiscriminators.Add(messageType.ToString()!, schema.Reference.ReferenceV3);
}
+ // Add custom "SyncPlayGroupUpdateMessage" schema because Swashbuckle cannot generate it for us
+ var syncPlayGroupUpdateMessageSchema = new OpenApiSchema
+ {
+ Type = "object",
+ Description = "Untyped sync play command.",
+ Properties = new Dictionary<string, OpenApiSchema>
+ {
+ {
+ "Data", new OpenApiSchema
+ {
+ AllOf =
+ [
+ new OpenApiSchema { Reference = new OpenApiReference { Type = ReferenceType.Schema, Id = nameof(GroupUpdate<object>) } }
+ ],
+ Description = "Group update data",
+ Nullable = false,
+ }
+ },
+ { "MessageId", new OpenApiSchema { Type = "string", Format = "uuid", Description = "Gets or sets the message id." } },
+ {
+ "MessageType", new OpenApiSchema
+ {
+ Enum = Enum.GetValues<SessionMessageType>().Select(type => new OpenApiString(type.ToString())).ToList<IOpenApiAny>(),
+ AllOf =
+ [
+ new OpenApiSchema { Reference = new OpenApiReference { Type = ReferenceType.Schema, Id = nameof(SessionMessageType) } }
+ ],
+ Description = "The different kinds of messages that are used in the WebSocket api.",
+ Default = new OpenApiString(nameof(SessionMessageType.SyncPlayGroupUpdate)),
+ ReadOnly = true
+ }
+ },
+ },
+ AdditionalPropertiesAllowed = false,
+ Reference = new OpenApiReference { Type = ReferenceType.Schema, Id = "SyncPlayGroupUpdateMessage" }
+ };
+ context.SchemaRepository.AddDefinition("SyncPlayGroupUpdateMessage", syncPlayGroupUpdateMessageSchema);
+ outboundWebSocketSchemas.Add(syncPlayGroupUpdateMessageSchema);
+ outboundWebSocketDiscriminators[nameof(SessionMessageType.SyncPlayGroupUpdate)] = syncPlayGroupUpdateMessageSchema.Reference.ReferenceV3;
+
var outboundWebSocketMessageSchema = new OpenApiSchema
{
Type = "object",
@@ -140,41 +174,46 @@ namespace Jellyfin.Server.Filters
});
// Manually generate sync play GroupUpdate messages.
- if (!context.SchemaRepository.Schemas.TryGetValue(nameof(GroupUpdate), out var groupUpdateSchema))
- {
- groupUpdateSchema = context.SchemaGenerator.GenerateSchema(typeof(GroupUpdate), context.SchemaRepository);
- }
-
- var groupUpdateOfGroupInfoSchema = context.SchemaGenerator.GenerateSchema(typeof(GroupUpdate<GroupInfoDto>), context.SchemaRepository);
- var groupUpdateOfGroupStateSchema = context.SchemaGenerator.GenerateSchema(typeof(GroupUpdate<GroupStateUpdate>), context.SchemaRepository);
- var groupUpdateOfStringSchema = context.SchemaGenerator.GenerateSchema(typeof(GroupUpdate<string>), context.SchemaRepository);
- var groupUpdateOfPlayQueueSchema = context.SchemaGenerator.GenerateSchema(typeof(GroupUpdate<PlayQueueUpdate>), context.SchemaRepository);
+ var groupUpdateTypes = typeof(GroupUpdate<>).Assembly.GetTypes()
+ .Where(t => t.BaseType != null
+ && t.BaseType.IsGenericType
+ && t.BaseType.GetGenericTypeDefinition() == typeof(GroupUpdate<>))
+ .ToList();
- groupUpdateSchema.OneOf = new List<OpenApiSchema>
+ var groupUpdateSchemas = new List<OpenApiSchema>();
+ var groupUpdateDiscriminators = new Dictionary<string, string>();
+ foreach (var type in groupUpdateTypes)
{
- groupUpdateOfGroupInfoSchema,
- groupUpdateOfGroupStateSchema,
- groupUpdateOfStringSchema,
- groupUpdateOfPlayQueueSchema
- };
+ var groupUpdateType = (GroupUpdateType?)type.GetProperty(nameof(GroupUpdate<object>.Type))?.GetCustomAttribute<DefaultValueAttribute>()?.Value;
+ if (groupUpdateType is null)
+ {
+ continue;
+ }
+
+ var schema = context.SchemaGenerator.GenerateSchema(type, context.SchemaRepository);
+ groupUpdateSchemas.Add(schema);
+ groupUpdateDiscriminators[groupUpdateType.ToString()!] = schema.Reference.ReferenceV3;
+ }
- groupUpdateSchema.Discriminator = new OpenApiDiscriminator
+ var groupUpdateSchema = new OpenApiSchema
{
- PropertyName = nameof(GroupUpdate.Type),
- Mapping = new Dictionary<string, string>
+ Type = "object",
+ Description = "Represents the list of possible group update types",
+ Reference = new OpenApiReference
+ {
+ Id = nameof(GroupUpdate<object>),
+ Type = ReferenceType.Schema
+ },
+ OneOf = groupUpdateSchemas,
+ Discriminator = new OpenApiDiscriminator
{
- { GroupUpdateType.UserJoined.ToString(), groupUpdateOfStringSchema.Reference.ReferenceV3 },
- { GroupUpdateType.UserLeft.ToString(), groupUpdateOfStringSchema.Reference.ReferenceV3 },
- { GroupUpdateType.GroupJoined.ToString(), groupUpdateOfGroupInfoSchema.Reference.ReferenceV3 },
- { GroupUpdateType.GroupLeft.ToString(), groupUpdateOfStringSchema.Reference.ReferenceV3 },
- { GroupUpdateType.StateUpdate.ToString(), groupUpdateOfGroupStateSchema.Reference.ReferenceV3 },
- { GroupUpdateType.PlayQueue.ToString(), groupUpdateOfPlayQueueSchema.Reference.ReferenceV3 },
- { GroupUpdateType.NotInGroup.ToString(), groupUpdateOfStringSchema.Reference.ReferenceV3 },
- { GroupUpdateType.GroupDoesNotExist.ToString(), groupUpdateOfStringSchema.Reference.ReferenceV3 },
- { GroupUpdateType.LibraryAccessDenied.ToString(), groupUpdateOfStringSchema.Reference.ReferenceV3 }
+ PropertyName = nameof(GroupUpdate<object>.Type),
+ Mapping = groupUpdateDiscriminators
}
};
+ context.SchemaRepository.Schemas[nameof(GroupUpdate<object>)] = groupUpdateSchema;
+
context.SchemaGenerator.GenerateSchema(typeof(ServerDiscoveryInfo), context.SchemaRepository);
foreach (var configuration in _serverConfigurationManager.GetConfigurationStores())
diff --git a/Jellyfin.Server/Helpers/StartupHelpers.cs b/Jellyfin.Server/Helpers/StartupHelpers.cs
index bbf6d31f1..93c996166 100644
--- a/Jellyfin.Server/Helpers/StartupHelpers.cs
+++ b/Jellyfin.Server/Helpers/StartupHelpers.cs
@@ -3,18 +3,19 @@ using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
-using System.Net;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading.Tasks;
using Emby.Server.Implementations;
+using Jellyfin.Server.ServerSetupApp;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Extensions;
using MediaBrowser.Model.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
+using Serilog.Extensions.Logging;
using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace Jellyfin.Server.Helpers;
@@ -257,11 +258,14 @@ public static class StartupHelpers
{
try
{
+ var startupLogger = new LoggerProviderCollection();
+ startupLogger.AddProvider(new SetupServer.SetupLoggerFactory());
// Serilog.Log is used by SerilogLoggerFactory when no logger is specified
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.Enrich.FromLogContext()
.Enrich.WithThreadId()
+ .WriteTo.Async(e => e.Providers(startupLogger))
.CreateLogger();
}
catch (Exception ex)
diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj
index 452b03efb..14c4285fe 100644
--- a/Jellyfin.Server/Jellyfin.Server.csproj
+++ b/Jellyfin.Server/Jellyfin.Server.csproj
@@ -48,6 +48,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration.Json" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" />
+ <PackageReference Include="Morestachio" />
<PackageReference Include="prometheus-net" />
<PackageReference Include="prometheus-net.AspNetCore" />
<PackageReference Include="Serilog.AspNetCore" />
@@ -79,6 +80,9 @@
<None Update="wwwroot\api-docs\banner-dark.svg">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
+ <None Update="ServerSetupApp/index.mstemplate.html">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </None>
</ItemGroup>
</Project>
diff --git a/Jellyfin.Server/Migrations/IAsyncMigrationRoutine.cs b/Jellyfin.Server/Migrations/IAsyncMigrationRoutine.cs
new file mode 100644
index 000000000..5b6a5fe94
--- /dev/null
+++ b/Jellyfin.Server/Migrations/IAsyncMigrationRoutine.cs
@@ -0,0 +1,31 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace Jellyfin.Server.Migrations;
+
+/// <summary>
+/// Interface that describes a migration routine.
+/// </summary>
+internal interface IAsyncMigrationRoutine
+{
+ /// <summary>
+ /// Execute the migration routine.
+ /// </summary>
+ /// <param name="cancellationToken">A cancellation token triggered if the migration should be aborted.</param>
+ /// <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 78ff1e3fd..d2d80a81e 100644
--- a/Jellyfin.Server/Migrations/IDatabaseMigrationRoutine.cs
+++ b/Jellyfin.Server/Migrations/IDatabaseMigrationRoutine.cs
@@ -7,6 +7,8 @@ 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
{
}
diff --git a/Jellyfin.Server/Migrations/IMigrationRoutine.cs b/Jellyfin.Server/Migrations/IMigrationRoutine.cs
deleted file mode 100644
index 29f681df5..000000000
--- a/Jellyfin.Server/Migrations/IMigrationRoutine.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-using System;
-using Jellyfin.Server.Implementations;
-using Microsoft.EntityFrameworkCore.Internal;
-
-namespace Jellyfin.Server.Migrations
-{
- /// <summary>
- /// Interface that describes a migration routine.
- /// </summary>
- internal interface IMigrationRoutine
- {
- /// <summary>
- /// Gets the unique id for this migration. This should never be modified after the migration has been created.
- /// </summary>
- public Guid Id { get; }
-
- /// <summary>
- /// Gets the display name of the migration.
- /// </summary>
- public string Name { get; }
-
- /// <summary>
- /// Gets a value indicating whether to perform migration on a new install.
- /// </summary>
- public bool PerformOnNewInstall { get; }
-
- /// <summary>
- /// Execute the migration routine.
- /// </summary>
- public void Perform();
- }
-}
diff --git a/Jellyfin.Server/Migrations/JellyfinMigrationAttribute.cs b/Jellyfin.Server/Migrations/JellyfinMigrationAttribute.cs
new file mode 100644
index 000000000..70e54125b
--- /dev/null
+++ b/Jellyfin.Server/Migrations/JellyfinMigrationAttribute.cs
@@ -0,0 +1,68 @@
+#pragma warning disable CA1019 // Define accessors for attribute arguments
+
+using System;
+using System.Globalization;
+using Jellyfin.Server.Migrations.Stages;
+
+namespace Jellyfin.Server.Migrations;
+
+/// <summary>
+/// Declares an class as an migration with its set metadata.
+/// </summary>
+[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
+public sealed class JellyfinMigrationAttribute : Attribute
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="JellyfinMigrationAttribute"/> class.
+ /// </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
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="JellyfinMigrationAttribute"/> class for legacy migrations.
+ /// </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>
+ /// <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);
+ Name = name;
+ Stage = JellyfinMigrationStageTypes.AppInitialisation;
+ if (key is not null)
+ {
+ Key = Guid.Parse(key);
+ }
+ }
+
+ /// <summary>
+ /// Gets or Sets a value indicating whether the annoated migration should be executed on a fresh install.
+ /// </summary>
+ public bool RunMigrationOnSetup { get; set; }
+
+ /// <summary>
+ /// Gets or Sets the stage the annoated migration should be executed at. Defaults to <see cref="JellyfinMigrationStageTypes.CoreInitialisation"/>.
+ /// </summary>
+ public JellyfinMigrationStageTypes Stage { get; set; } = JellyfinMigrationStageTypes.CoreInitialisation;
+
+ /// <summary>
+ /// Gets the ordering of the migration.
+ /// </summary>
+ public DateTime Order { get; }
+
+ /// <summary>
+ /// Gets the name of the migration.
+ /// </summary>
+ public string Name { get; }
+
+ /// <summary>
+ /// Gets the Legacy Key of the migration. Not required for new Migrations.
+ /// </summary>
+ public Guid? Key { get; }
+}
diff --git a/Jellyfin.Server/Migrations/JellyfinMigrationBackupAttribute.cs b/Jellyfin.Server/Migrations/JellyfinMigrationBackupAttribute.cs
new file mode 100644
index 000000000..6c8da7e82
--- /dev/null
+++ b/Jellyfin.Server/Migrations/JellyfinMigrationBackupAttribute.cs
@@ -0,0 +1,35 @@
+using System;
+
+namespace Jellyfin.Server.Migrations;
+
+/// <summary>
+/// Marks an <see cref="JellyfinMigrationAttribute"/> migration and instructs the <see cref="JellyfinMigrationService"/> to perform a backup.
+/// </summary>
+[AttributeUsage(System.AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
+public sealed class JellyfinMigrationBackupAttribute : System.Attribute
+{
+ /// <summary>
+ /// Gets or Sets a value indicating whether a backup of the old library.db should be performed.
+ /// </summary>
+ public bool LegacyLibraryDb { get; set; }
+
+ /// <summary>
+ /// Gets or Sets a value indicating whether a backup of the Database should be performed.
+ /// </summary>
+ public bool JellyfinDb { get; set; }
+
+ /// <summary>
+ /// Gets or Sets a value indicating whether a backup of the metadata folder should be performed.
+ /// </summary>
+ public bool Metadata { get; set; }
+
+ /// <summary>
+ /// Gets or Sets a value indicating whether a backup of the Trickplay folder should be performed.
+ /// </summary>
+ public bool Trickplay { get; set; }
+
+ /// <summary>
+ /// Gets or Sets a value indicating whether a backup of the Subtitles folder should be performed.
+ /// </summary>
+ public bool Subtitles { get; set; }
+}
diff --git a/Jellyfin.Server/Migrations/JellyfinMigrationService.cs b/Jellyfin.Server/Migrations/JellyfinMigrationService.cs
new file mode 100644
index 000000000..5331b43e3
--- /dev/null
+++ b/Jellyfin.Server/Migrations/JellyfinMigrationService.cs
@@ -0,0 +1,451 @@
+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 Emby.Server.Implementations.Serialization;
+using Jellyfin.Database.Implementations;
+using Jellyfin.Server.Implementations.SystemBackupService;
+using Jellyfin.Server.Migrations.Stages;
+using Jellyfin.Server.ServerSetupApp;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.SystemBackupService;
+using MediaBrowser.Model.Configuration;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Migrations;
+
+/// <summary>
+/// Handles Migration of the Jellyfin data structure.
+/// </summary>
+internal class JellyfinMigrationService
+{
+ private const string DbFilename = "library.db";
+ private readonly IDbContextFactory<JellyfinDbContext> _dbContextFactory;
+ private readonly ILoggerFactory _loggerFactory;
+ private readonly IStartupLogger _startupLogger;
+ private readonly IBackupService? _backupService;
+ private readonly IJellyfinDatabaseProvider? _jellyfinDatabaseProvider;
+ private readonly IApplicationPaths _applicationPaths;
+ private (string? LibraryDb, string? JellyfinDb, BackupManifestDto? FullBackup) _backupKey;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="JellyfinMigrationService"/> class.
+ /// </summary>
+ /// <param name="dbContextFactory">Provides access to the jellyfin database.</param>
+ /// <param name="loggerFactory">The logger factory.</param>
+ /// <param name="startupLogger">The startup logger for Startup UI intigration.</param>
+ /// <param name="applicationPaths">Application paths for library.db backup.</param>
+ /// <param name="backupService">The jellyfin backup service.</param>
+ /// <param name="jellyfinDatabaseProvider">The jellyfin database provider.</param>
+ public JellyfinMigrationService(
+ IDbContextFactory<JellyfinDbContext> dbContextFactory,
+ ILoggerFactory loggerFactory,
+ IStartupLogger startupLogger,
+ IApplicationPaths applicationPaths,
+ IBackupService? backupService = null,
+ IJellyfinDatabaseProvider? jellyfinDatabaseProvider = null)
+ {
+ _dbContextFactory = dbContextFactory;
+ _loggerFactory = loggerFactory;
+ _startupLogger = startupLogger;
+ _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))
+ .Select(e => (Type: e, Metadata: e.GetCustomAttribute<JellyfinMigrationAttribute>(), Backup: e.GetCustomAttributes<JellyfinMigrationBackupAttribute>()))
+ .Where(e => e.Metadata != null)
+ .GroupBy(e => e.Metadata!.Stage)
+ .Select(f =>
+ {
+ var stage = new MigrationStage(f.Key);
+ foreach (var item in f)
+ {
+ JellyfinMigrationBackupAttribute? backupMetadata = null;
+ if (item.Backup?.Any() == true)
+ {
+ backupMetadata = item.Backup.Aggregate(MergeBackupAttributes);
+ }
+
+ stage.Add(new(item.Type, item.Metadata!, backupMetadata));
+ }
+
+ return stage;
+ })];
+#pragma warning restore CS0618 // Type or member is obsolete
+ }
+
+ private interface IInternalMigration
+ {
+ Task PerformAsync(IStartupLogger logger);
+ }
+
+ private HashSet<MigrationStage> Migrations { get; set; }
+
+ public async Task CheckFirstTimeRunOrMigration(IApplicationPaths appPaths)
+ {
+ var logger = _startupLogger.With(_loggerFactory.CreateLogger<JellyfinMigrationService>()).BeginGroup($"Migration Startup");
+ logger.LogInformation("Initialise Migration service.");
+ var xmlSerializer = new MyXmlSerializer();
+ var serverConfig = File.Exists(appPaths.SystemConfigurationFilePath)
+ ? (ServerConfiguration)xmlSerializer.DeserializeFromFile(typeof(ServerConfiguration), appPaths.SystemConfigurationFilePath)!
+ : new ServerConfiguration();
+ if (!serverConfig.IsStartupWizardCompleted)
+ {
+ logger.LogInformation("System initialisation detected. Seed data.");
+ var flatApplyMigrations = Migrations.SelectMany(e => e.Where(f => !f.Metadata.RunMigrationOnSetup)).ToArray();
+
+ var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false);
+ await using (dbContext.ConfigureAwait(false))
+ {
+ var historyRepository = dbContext.GetService<IHistoryRepository>();
+
+ await historyRepository.CreateIfNotExistsAsync().ConfigureAwait(false);
+ var appliedMigrations = await dbContext.Database.GetAppliedMigrationsAsync().ConfigureAwait(false);
+ var startupScripts = flatApplyMigrations
+ .Where(e => !appliedMigrations.Any(f => f != e.BuildCodeMigrationId()))
+ .Select(e => (Migration: e.Metadata, Script: historyRepository.GetInsertScript(new HistoryRow(e.BuildCodeMigrationId(), GetJellyfinVersion()))))
+ .ToArray();
+ foreach (var item in startupScripts)
+ {
+ logger.LogInformation("Seed migration {Key}-{Name}.", item.Migration.Key, item.Migration.Name);
+ await dbContext.Database.ExecuteSqlRawAsync(item.Script).ConfigureAwait(false);
+ }
+ }
+
+ logger.LogInformation("Migration system initialisation completed.");
+ }
+ else
+ {
+ // migrate any existing migration.xml files
+ var migrationConfigPath = Path.Join(appPaths.ConfigurationDirectoryPath, "migrations.xml");
+ var migrationOptions = File.Exists(migrationConfigPath)
+ ? (MigrationOptions)xmlSerializer.DeserializeFromFile(typeof(MigrationOptions), migrationConfigPath)!
+ : null;
+ if (migrationOptions != null && migrationOptions.Applied.Count > 0)
+ {
+ logger.LogInformation("Old migration style migration.xml detected. Migrate now.");
+ try
+ {
+ var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false);
+ await using (dbContext.ConfigureAwait(false))
+ {
+ var historyRepository = dbContext.GetService<IHistoryRepository>();
+ var appliedMigrations = await dbContext.Database.GetAppliedMigrationsAsync().ConfigureAwait(false);
+ var lastOldAppliedMigration = Migrations
+ .SelectMany(e => e.Where(e => e.Metadata.Key is not null)) // only consider migrations that have the key set as its the reference marker for legacy migrations.
+ .Where(e => migrationOptions.Applied.Any(f => f.Id.Equals(e.Metadata.Key!.Value)))
+ .Where(e => !appliedMigrations.Contains(e.BuildCodeMigrationId()))
+ .OrderBy(e => e.BuildCodeMigrationId())
+ .Last(); // this is the latest migration applied in the old migration.xml
+
+ IReadOnlyList<CodeMigration> oldMigrations = [
+ .. Migrations
+ .SelectMany(e => e)
+ .OrderBy(e => e.BuildCodeMigrationId())
+ .TakeWhile(e => e.BuildCodeMigrationId() != lastOldAppliedMigration.BuildCodeMigrationId()),
+ lastOldAppliedMigration
+ ];
+ // those are all migrations that had to run in the old migration system, even if not noted in the migration.xml file.
+
+ var startupScripts = oldMigrations.Select(e => (Migration: e.Metadata, Script: historyRepository.GetInsertScript(new HistoryRow(e.BuildCodeMigrationId(), GetJellyfinVersion()))));
+ foreach (var item in startupScripts)
+ {
+ logger.LogInformation("Migrate migration {Key}-{Name}.", item.Migration.Key, item.Migration.Name);
+ await dbContext.Database.ExecuteSqlRawAsync(item.Script).ConfigureAwait(false);
+ }
+
+ logger.LogInformation("Rename old migration.xml to migration.xml.backup");
+ File.Move(migrationConfigPath, Path.ChangeExtension(migrationConfigPath, ".xml.backup"), true);
+ }
+ }
+ catch (Exception ex)
+ {
+ logger.LogCritical(ex, "Failed to apply migrations");
+ throw;
+ }
+ }
+ }
+ }
+
+ public async Task MigrateStepAsync(JellyfinMigrationStageTypes stage, IServiceProvider? serviceProvider)
+ {
+ var logger = _startupLogger.With(_loggerFactory.CreateLogger<JellyfinMigrationService>()).BeginGroup($"Migrate stage {stage}.");
+ ICollection<CodeMigration> migrationStage = (Migrations.FirstOrDefault(e => e.Stage == stage) as ICollection<CodeMigration>) ?? [];
+
+ var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false);
+ await using (dbContext.ConfigureAwait(false))
+ {
+ var historyRepository = dbContext.GetService<IHistoryRepository>();
+ var migrationsAssembly = dbContext.GetService<IMigrationsAssembly>();
+ var appliedMigrations = await historyRepository.GetAppliedMigrationsAsync().ConfigureAwait(false);
+ var pendingCodeMigrations = migrationStage
+ .Where(e => appliedMigrations.All(f => f.MigrationId != e.BuildCodeMigrationId()))
+ .Select(e => (Key: e.BuildCodeMigrationId(), Migration: new InternalCodeMigration(e, serviceProvider, dbContext)))
+ .ToArray();
+
+ (string Key, InternalDatabaseMigration Migration)[] pendingDatabaseMigrations = [];
+ if (stage is JellyfinMigrationStageTypes.CoreInitialisation)
+ {
+ pendingDatabaseMigrations = migrationsAssembly.Migrations.Where(f => appliedMigrations.All(e => e.MigrationId != f.Key))
+ .Select(e => (Key: e.Key, Migration: new InternalDatabaseMigration(e, dbContext)))
+ .ToArray();
+ }
+
+ (string Key, IInternalMigration Migration)[] pendingMigrations = [.. pendingCodeMigrations, .. pendingDatabaseMigrations];
+ logger.LogInformation("There are {Pending} migrations for stage {Stage}.", pendingCodeMigrations.Length, stage);
+ var migrations = pendingMigrations.OrderBy(e => e.Key).ToArray();
+
+ foreach (var item in migrations)
+ {
+ var migrationLogger = logger.With(_loggerFactory.CreateLogger(item.Migration.GetType().Name)).BeginGroup($"{item.Key}");
+ try
+ {
+ migrationLogger.LogInformation("Perform migration {Name}", item.Key);
+ await item.Migration.PerformAsync(migrationLogger).ConfigureAwait(false);
+ migrationLogger.LogInformation("Migration {Name} was successfully applied", item.Key);
+ }
+ catch (Exception ex)
+ {
+ migrationLogger.LogCritical("Error: {Error}", ex.Message);
+ migrationLogger.LogError(ex, "Migration {Name} failed", item.Key);
+
+ if (_backupKey != default && _backupService is not null && _jellyfinDatabaseProvider is not null)
+ {
+ if (_backupKey.LibraryDb is not null)
+ {
+ migrationLogger.LogInformation("Attempt to rollback librarydb.");
+ try
+ {
+ var libraryDbPath = Path.Combine(_applicationPaths.DataPath, DbFilename);
+ File.Move(_backupKey.LibraryDb, libraryDbPath, true);
+ }
+ catch (Exception inner)
+ {
+ migrationLogger.LogCritical(inner, "Could not rollback {LibraryPath}. Manual intervention might be required to restore a operational state.", _backupKey.LibraryDb);
+ }
+ }
+
+ if (_backupKey.JellyfinDb is not null)
+ {
+ migrationLogger.LogInformation("Attempt to rollback JellyfinDb.");
+ try
+ {
+ await _jellyfinDatabaseProvider.RestoreBackupFast(_backupKey.JellyfinDb, CancellationToken.None).ConfigureAwait(false);
+ }
+ catch (Exception inner)
+ {
+ migrationLogger.LogCritical(inner, "Could not rollback {LibraryPath}. Manual intervention might be required to restore a operational state.", _backupKey.JellyfinDb);
+ }
+ }
+
+ if (_backupKey.FullBackup is not null)
+ {
+ migrationLogger.LogInformation("Attempt to rollback from backup.");
+ try
+ {
+ await _backupService.RestoreBackupAsync(_backupKey.FullBackup.Path).ConfigureAwait(false);
+ }
+ catch (Exception inner)
+ {
+ migrationLogger.LogCritical(inner, "Could not rollback from backup {Backup}. Manual intervention might be required to restore a operational state.", _backupKey.FullBackup.Path);
+ }
+ }
+ }
+
+ throw;
+ }
+ }
+ }
+ }
+
+ private static string GetJellyfinVersion()
+ {
+ return Assembly.GetEntryAssembly()!.GetName().Version!.ToString();
+ }
+
+ public async Task CleanupSystemAfterMigration(ILogger logger)
+ {
+ if (_backupKey != default)
+ {
+ if (_backupKey.LibraryDb is not null)
+ {
+ logger.LogInformation("Attempt to cleanup librarydb backup.");
+ try
+ {
+ File.Delete(_backupKey.LibraryDb);
+ }
+ catch (Exception inner)
+ {
+ logger.LogCritical(inner, "Could not cleanup {LibraryPath}.", _backupKey.LibraryDb);
+ }
+ }
+
+ if (_backupKey.JellyfinDb is not null && _jellyfinDatabaseProvider is not null)
+ {
+ logger.LogInformation("Attempt to cleanup JellyfinDb backup.");
+ try
+ {
+ await _jellyfinDatabaseProvider.DeleteBackup(_backupKey.JellyfinDb).ConfigureAwait(false);
+ }
+ catch (Exception inner)
+ {
+ logger.LogCritical(inner, "Could not cleanup {LibraryPath}.", _backupKey.JellyfinDb);
+ }
+ }
+
+ if (_backupKey.FullBackup is not null)
+ {
+ logger.LogInformation("Attempt to cleanup from migration backup.");
+ try
+ {
+ File.Delete(_backupKey.FullBackup.Path);
+ }
+ catch (Exception inner)
+ {
+ logger.LogCritical(inner, "Could not cleanup backup {Backup}.", _backupKey.FullBackup.Path);
+ }
+ }
+ }
+ }
+
+ public async Task PrepareSystemForMigration(ILogger logger)
+ {
+ logger.LogInformation("Prepare system for possible migrations");
+ JellyfinMigrationBackupAttribute backupInstruction;
+ IReadOnlyList<HistoryRow> appliedMigrations;
+ var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false);
+ await using (dbContext.ConfigureAwait(false))
+ {
+ var historyRepository = dbContext.GetService<IHistoryRepository>();
+ var migrationsAssembly = dbContext.GetService<IMigrationsAssembly>();
+ appliedMigrations = await historyRepository.GetAppliedMigrationsAsync().ConfigureAwait(false);
+ backupInstruction = new JellyfinMigrationBackupAttribute()
+ {
+ JellyfinDb = migrationsAssembly.Migrations.Any(f => appliedMigrations.All(e => e.MigrationId != f.Key))
+ };
+ }
+
+ backupInstruction = Migrations.SelectMany(e => e)
+ .Where(e => appliedMigrations.All(f => f.MigrationId != e.BuildCodeMigrationId()))
+ .Select(e => e.BackupRequirements)
+ .Where(e => e is not null)
+ .Aggregate(backupInstruction, MergeBackupAttributes!);
+
+ if (backupInstruction.LegacyLibraryDb)
+ {
+ logger.LogInformation("A migration will attempt to modify the library.db, will attempt to backup the file now.");
+ // for legacy migrations that still operates on the library.db
+ var libraryDbPath = Path.Combine(_applicationPaths.DataPath, DbFilename);
+ if (File.Exists(libraryDbPath))
+ {
+ for (int i = 1; ; i++)
+ {
+ var bakPath = string.Format(CultureInfo.InvariantCulture, "{0}.bak{1}", libraryDbPath, i);
+ if (!File.Exists(bakPath))
+ {
+ try
+ {
+ logger.LogInformation("Backing up {Library} to {BackupPath}", DbFilename, bakPath);
+ File.Copy(libraryDbPath, bakPath);
+ _backupKey = (bakPath, _backupKey.JellyfinDb, _backupKey.FullBackup);
+ logger.LogInformation("{Library} backed up to {BackupPath}", DbFilename, bakPath);
+ break;
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(ex, "Cannot make a backup of {Library} at path {BackupPath}", DbFilename, bakPath);
+ throw;
+ }
+ }
+ }
+
+ logger.LogInformation("{Library} has been backed up as {BackupPath}", DbFilename, _backupKey.LibraryDb);
+ }
+ else
+ {
+ logger.LogError("Cannot make a backup of {Library} at path {BackupPath} because file could not be found at {LibraryPath}", DbFilename, libraryDbPath, _applicationPaths.DataPath);
+ }
+ }
+
+ if (backupInstruction.JellyfinDb && _jellyfinDatabaseProvider != null)
+ {
+ logger.LogInformation("A migration will attempt to modify the jellyfin.db, will attempt to backup the file now.");
+ _backupKey = (_backupKey.LibraryDb, await _jellyfinDatabaseProvider.MigrationBackupFast(CancellationToken.None).ConfigureAwait(false), _backupKey.FullBackup);
+ logger.LogInformation("Jellyfin database has been backed up as {BackupPath}", _backupKey.JellyfinDb);
+ }
+
+ if (_backupService is not null && (backupInstruction.Metadata || backupInstruction.Subtitles || backupInstruction.Trickplay))
+ {
+ logger.LogInformation("A migration will attempt to modify system resources. Will attempt to create backup now.");
+ _backupKey = (_backupKey.LibraryDb, _backupKey.JellyfinDb, await _backupService.CreateBackupAsync(new BackupOptionsDto()
+ {
+ Metadata = backupInstruction.Metadata,
+ Subtitles = backupInstruction.Subtitles,
+ Trickplay = backupInstruction.Trickplay,
+ Database = false // database backups are explicitly handled by the provider itself as the backup service requires parity with the current model
+ }).ConfigureAwait(false));
+ logger.LogInformation("Pre-Migration backup successfully created as {BackupKey}", _backupKey.FullBackup.Path);
+ }
+ }
+
+ private static JellyfinMigrationBackupAttribute MergeBackupAttributes(JellyfinMigrationBackupAttribute left, JellyfinMigrationBackupAttribute right)
+ {
+ return new JellyfinMigrationBackupAttribute()
+ {
+ JellyfinDb = left!.JellyfinDb || right!.JellyfinDb,
+ LegacyLibraryDb = left.LegacyLibraryDb || right!.LegacyLibraryDb,
+ Metadata = left.Metadata || right!.Metadata,
+ Subtitles = left.Subtitles || right!.Subtitles,
+ Trickplay = left.Trickplay || right!.Trickplay
+ };
+ }
+
+ private class InternalCodeMigration : IInternalMigration
+ {
+ private readonly CodeMigration _codeMigration;
+ private readonly IServiceProvider? _serviceProvider;
+ private JellyfinDbContext _dbContext;
+
+ public InternalCodeMigration(CodeMigration codeMigration, IServiceProvider? serviceProvider, JellyfinDbContext dbContext)
+ {
+ _codeMigration = codeMigration;
+ _serviceProvider = serviceProvider;
+ _dbContext = dbContext;
+ }
+
+ public async Task PerformAsync(IStartupLogger logger)
+ {
+ await _codeMigration.Perform(_serviceProvider, logger, CancellationToken.None).ConfigureAwait(false);
+
+ var historyRepository = _dbContext.GetService<IHistoryRepository>();
+ var createScript = historyRepository.GetInsertScript(new HistoryRow(_codeMigration.BuildCodeMigrationId(), GetJellyfinVersion()));
+ await _dbContext.Database.ExecuteSqlRawAsync(createScript).ConfigureAwait(false);
+ }
+ }
+
+ private class InternalDatabaseMigration : IInternalMigration
+ {
+ private readonly JellyfinDbContext _jellyfinDbContext;
+ private KeyValuePair<string, TypeInfo> _databaseMigrationInfo;
+
+ public InternalDatabaseMigration(KeyValuePair<string, TypeInfo> databaseMigrationInfo, JellyfinDbContext jellyfinDbContext)
+ {
+ _databaseMigrationInfo = databaseMigrationInfo;
+ _jellyfinDbContext = jellyfinDbContext;
+ }
+
+ public async Task PerformAsync(IStartupLogger logger)
+ {
+ var migrator = _jellyfinDbContext.GetService<IMigrator>();
+ await migrator.MigrateAsync(_databaseMigrationInfo.Key).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/Jellyfin.Server/Migrations/MigrationRunner.cs b/Jellyfin.Server/Migrations/MigrationRunner.cs
deleted file mode 100644
index 9865199f3..000000000
--- a/Jellyfin.Server/Migrations/MigrationRunner.cs
+++ /dev/null
@@ -1,181 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Emby.Server.Implementations;
-using Emby.Server.Implementations.Serialization;
-using Jellyfin.Database.Implementations;
-using Jellyfin.Server.Implementations;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Model.Configuration;
-using Microsoft.EntityFrameworkCore.Storage;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Logging;
-
-namespace Jellyfin.Server.Migrations
-{
- /// <summary>
- /// The class that knows which migrations to apply and how to apply them.
- /// </summary>
- public sealed class MigrationRunner
- {
- /// <summary>
- /// The list of known pre-startup migrations, in order of applicability.
- /// </summary>
- private static readonly Type[] _preStartupMigrationTypes =
- {
- typeof(PreStartupRoutines.CreateNetworkConfiguration),
- typeof(PreStartupRoutines.MigrateMusicBrainzTimeout),
- typeof(PreStartupRoutines.MigrateNetworkConfiguration),
- typeof(PreStartupRoutines.MigrateEncodingOptions),
- typeof(PreStartupRoutines.RenameEnableGroupingIntoCollections)
- };
-
- /// <summary>
- /// The list of known migrations, in order of applicability.
- /// </summary>
- private static readonly Type[] _migrationTypes =
- {
- typeof(Routines.DisableTranscodingThrottling),
- typeof(Routines.CreateUserLoggingConfigFile),
- typeof(Routines.MigrateActivityLogDb),
- typeof(Routines.RemoveDuplicateExtras),
- typeof(Routines.AddDefaultPluginRepository),
- typeof(Routines.MigrateUserDb),
- typeof(Routines.ReaddDefaultPluginRepository),
- typeof(Routines.MigrateDisplayPreferencesDb),
- typeof(Routines.RemoveDownloadImagesInAdvance),
- typeof(Routines.MigrateAuthenticationDb),
- typeof(Routines.FixPlaylistOwner),
- typeof(Routines.MigrateRatingLevels),
- typeof(Routines.AddDefaultCastReceivers),
- typeof(Routines.UpdateDefaultPluginRepository),
- typeof(Routines.FixAudioData),
- typeof(Routines.MoveTrickplayFiles),
- typeof(Routines.RemoveDuplicatePlaylistChildren),
- typeof(Routines.MigrateLibraryDb),
- };
-
- /// <summary>
- /// Run all needed migrations.
- /// </summary>
- /// <param name="host">CoreAppHost that hosts current version.</param>
- /// <param name="loggerFactory">Factory for making the logger.</param>
- /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
- public static async Task Run(CoreAppHost host, ILoggerFactory loggerFactory)
- {
- var logger = loggerFactory.CreateLogger<MigrationRunner>();
- var migrations = _migrationTypes
- .Select(m => ActivatorUtilities.CreateInstance(host.ServiceProvider, m))
- .OfType<IMigrationRoutine>()
- .ToArray();
-
- var migrationOptions = host.ConfigurationManager.GetConfiguration<MigrationOptions>(MigrationsListStore.StoreKey);
- HandleStartupWizardCondition(migrations, migrationOptions, host.ConfigurationManager.Configuration.IsStartupWizardCompleted, logger);
- await PerformMigrations(migrations, migrationOptions, options => host.ConfigurationManager.SaveConfiguration(MigrationsListStore.StoreKey, options), logger, host.ServiceProvider.GetRequiredService<IJellyfinDatabaseProvider>())
- .ConfigureAwait(false);
- }
-
- /// <summary>
- /// Run all needed pre-startup migrations.
- /// </summary>
- /// <param name="appPaths">Application paths.</param>
- /// <param name="loggerFactory">Factory for making the logger.</param>
- /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
- public static async Task RunPreStartup(ServerApplicationPaths appPaths, ILoggerFactory loggerFactory)
- {
- var logger = loggerFactory.CreateLogger<MigrationRunner>();
- var migrations = _preStartupMigrationTypes
- .Select(m => Activator.CreateInstance(m, appPaths, loggerFactory))
- .OfType<IMigrationRoutine>()
- .ToArray();
-
- var xmlSerializer = new MyXmlSerializer();
- var migrationConfigPath = Path.Join(appPaths.ConfigurationDirectoryPath, MigrationsListStore.StoreKey.ToLowerInvariant() + ".xml");
- var migrationOptions = File.Exists(migrationConfigPath)
- ? (MigrationOptions)xmlSerializer.DeserializeFromFile(typeof(MigrationOptions), migrationConfigPath)!
- : new MigrationOptions();
-
- // We have to deserialize it manually since the configuration manager may overwrite it
- var serverConfig = File.Exists(appPaths.SystemConfigurationFilePath)
- ? (ServerConfiguration)xmlSerializer.DeserializeFromFile(typeof(ServerConfiguration), appPaths.SystemConfigurationFilePath)!
- : new ServerConfiguration();
-
- HandleStartupWizardCondition(migrations, migrationOptions, serverConfig.IsStartupWizardCompleted, logger);
- await PerformMigrations(migrations, migrationOptions, options => xmlSerializer.SerializeToFile(options, migrationConfigPath), logger, null).ConfigureAwait(false);
- }
-
- private static void HandleStartupWizardCondition(IEnumerable<IMigrationRoutine> migrations, MigrationOptions migrationOptions, bool isStartWizardCompleted, ILogger logger)
- {
- if (isStartWizardCompleted)
- {
- return;
- }
-
- // If startup wizard is not finished, this is a fresh install.
- var onlyOldInstalls = migrations.Where(m => !m.PerformOnNewInstall).ToArray();
- logger.LogInformation("Marking following migrations as applied because this is a fresh install: {@OnlyOldInstalls}", onlyOldInstalls.Select(m => m.Name));
- migrationOptions.Applied.AddRange(onlyOldInstalls.Select(m => (m.Id, m.Name)));
- }
-
- private static async Task PerformMigrations(
- IMigrationRoutine[] migrations,
- MigrationOptions migrationOptions,
- Action<MigrationOptions> saveConfiguration,
- ILogger logger,
- IJellyfinDatabaseProvider? jellyfinDatabaseProvider)
- {
- // save already applied migrations, and skip them thereafter
- saveConfiguration(migrationOptions);
- var appliedMigrationIds = migrationOptions.Applied.Select(m => m.Id).ToHashSet();
- var migrationsToBeApplied = migrations.Where(e => !appliedMigrationIds.Contains(e.Id)).ToArray();
-
- string? migrationKey = null;
- if (jellyfinDatabaseProvider is not null && migrationsToBeApplied.Any(f => f is IDatabaseMigrationRoutine))
- {
- logger.LogInformation("Performing database backup");
- try
- {
- migrationKey = await jellyfinDatabaseProvider.MigrationBackupFast(CancellationToken.None).ConfigureAwait(false);
- logger.LogInformation("Database backup with key '{BackupKey}' has been successfully created.", migrationKey);
- }
- catch (NotImplementedException)
- {
- logger.LogWarning("Could not perform backup of database before migration because provider does not support it");
- }
- }
-
- try
- {
- foreach (var migrationRoutine in migrationsToBeApplied)
- {
- logger.LogInformation("Applying migration '{Name}'", migrationRoutine.Name);
-
- try
- {
- migrationRoutine.Perform();
- }
- catch (Exception ex)
- {
- logger.LogError(ex, "Could not apply migration '{Name}'", migrationRoutine.Name);
- throw;
- }
-
- // Mark the migration as completed
- logger.LogInformation("Migration '{Name}' applied successfully", migrationRoutine.Name);
- migrationOptions.Applied.Add((migrationRoutine.Id, migrationRoutine.Name));
- saveConfiguration(migrationOptions);
- logger.LogDebug("Migration '{Name}' marked as applied in configuration.", migrationRoutine.Name);
- }
- }
- catch (System.Exception) when (migrationKey is not null && jellyfinDatabaseProvider is not null)
- {
- logger.LogInformation("Rollback on database as migration reported failure.");
- await jellyfinDatabaseProvider.RestoreBackupFast(migrationKey, CancellationToken.None).ConfigureAwait(false);
- throw;
- }
- }
- }
-}
diff --git a/Jellyfin.Server/Migrations/MigrationsFactory.cs b/Jellyfin.Server/Migrations/MigrationsFactory.cs
deleted file mode 100644
index 23c1b1ee6..000000000
--- a/Jellyfin.Server/Migrations/MigrationsFactory.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-using System.Collections.Generic;
-using MediaBrowser.Common.Configuration;
-
-namespace Jellyfin.Server.Migrations
-{
- /// <summary>
- /// A factory that can find a persistent file of the migration configuration, which lists all applied migrations.
- /// </summary>
- public class MigrationsFactory : IConfigurationFactory
- {
- /// <inheritdoc/>
- public IEnumerable<ConfigurationStore> GetConfigurations()
- {
- return new[]
- {
- new MigrationsListStore()
- };
- }
- }
-}
diff --git a/Jellyfin.Server/Migrations/MigrationsListStore.cs b/Jellyfin.Server/Migrations/MigrationsListStore.cs
deleted file mode 100644
index 7a1ca6671..000000000
--- a/Jellyfin.Server/Migrations/MigrationsListStore.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-using MediaBrowser.Common.Configuration;
-
-namespace Jellyfin.Server.Migrations
-{
- /// <summary>
- /// A configuration that lists all the migration routines that were applied.
- /// </summary>
- public class MigrationsListStore : ConfigurationStore
- {
- /// <summary>
- /// The name of the configuration in the storage.
- /// </summary>
- public static readonly string StoreKey = "migrations";
-
- /// <summary>
- /// Initializes a new instance of the <see cref="MigrationsListStore"/> class.
- /// </summary>
- public MigrationsListStore()
- {
- ConfigurationType = typeof(MigrationOptions);
- Key = StoreKey;
- }
- }
-}
diff --git a/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs b/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs
index 8462d0a8c..fd472cff7 100644
--- a/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs
+++ b/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs
@@ -8,7 +8,10 @@ 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
{
private readonly ServerApplicationPaths _applicationPaths;
private readonly ILogger<CreateNetworkConfiguration> _logger;
@@ -25,15 +28,6 @@ public class CreateNetworkConfiguration : IMigrationRoutine
}
/// <inheritdoc />
- public Guid Id => Guid.Parse("9B354818-94D5-4B68-AC49-E35CB85F9D84");
-
- /// <inheritdoc />
- public string Name => nameof(CreateNetworkConfiguration);
-
- /// <inheritdoc />
- public bool PerformOnNewInstall => false;
-
- /// <inheritdoc />
public void Perform()
{
string path = Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "network.xml");
diff --git a/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateEncodingOptions.cs b/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateEncodingOptions.cs
index 61f5620dc..0141b43c9 100644
--- a/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateEncodingOptions.cs
+++ b/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateEncodingOptions.cs
@@ -10,7 +10,10 @@ 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
{
private readonly ServerApplicationPaths _applicationPaths;
private readonly ILogger<MigrateEncodingOptions> _logger;
@@ -27,15 +30,6 @@ public class MigrateEncodingOptions : IMigrationRoutine
}
/// <inheritdoc />
- public Guid Id => Guid.Parse("A8E61960-7726-4450-8F3D-82C12DAABBCB");
-
- /// <inheritdoc />
- public string Name => nameof(MigrateEncodingOptions);
-
- /// <inheritdoc />
- public bool PerformOnNewInstall => false;
-
- /// <inheritdoc />
public void Perform()
{
string path = Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "encoding.xml");
diff --git a/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateMusicBrainzTimeout.cs b/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateMusicBrainzTimeout.cs
index 580282a5f..e8da9f515 100644
--- a/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateMusicBrainzTimeout.cs
+++ b/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateMusicBrainzTimeout.cs
@@ -9,7 +9,10 @@ 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
{
private readonly ServerApplicationPaths _applicationPaths;
private readonly ILogger<MigrateMusicBrainzTimeout> _logger;
@@ -26,15 +29,6 @@ public class MigrateMusicBrainzTimeout : IMigrationRoutine
}
/// <inheritdoc />
- public Guid Id => Guid.Parse("A6DCACF4-C057-4Ef9-80D3-61CEF9DDB4F0");
-
- /// <inheritdoc />
- public string Name => nameof(MigrateMusicBrainzTimeout);
-
- /// <inheritdoc />
- public bool PerformOnNewInstall => false;
-
- /// <inheritdoc />
public void Perform()
{
string path = Path.Combine(_applicationPaths.PluginConfigurationsPath, "Jellyfin.Plugin.MusicBrainz.xml");
diff --git a/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateNetworkConfiguration.cs b/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateNetworkConfiguration.cs
index 09b292171..f2790c1a1 100644
--- a/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateNetworkConfiguration.cs
+++ b/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateNetworkConfiguration.cs
@@ -11,6 +11,7 @@ using Microsoft.Extensions.Logging;
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
{
private readonly ServerApplicationPaths _applicationPaths;
@@ -28,15 +29,6 @@ public class MigrateNetworkConfiguration : IMigrationRoutine
}
/// <inheritdoc />
- public Guid Id => Guid.Parse("4FB5C950-1991-11EE-9B4B-0800200C9A66");
-
- /// <inheritdoc />
- public string Name => nameof(MigrateNetworkConfiguration);
-
- /// <inheritdoc />
- public bool PerformOnNewInstall => false;
-
- /// <inheritdoc />
public void Perform()
{
string path = Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "network.xml");
diff --git a/Jellyfin.Server/Migrations/PreStartupRoutines/RenameEnableGroupingIntoCollections.cs b/Jellyfin.Server/Migrations/PreStartupRoutines/RenameEnableGroupingIntoCollections.cs
index 0a37b35a6..995b2bbf9 100644
--- a/Jellyfin.Server/Migrations/PreStartupRoutines/RenameEnableGroupingIntoCollections.cs
+++ b/Jellyfin.Server/Migrations/PreStartupRoutines/RenameEnableGroupingIntoCollections.cs
@@ -9,7 +9,10 @@ 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
{
private readonly ServerApplicationPaths _applicationPaths;
private readonly ILogger<RenameEnableGroupingIntoCollections> _logger;
@@ -26,15 +29,6 @@ public class RenameEnableGroupingIntoCollections : IMigrationRoutine
}
/// <inheritdoc />
- public Guid Id => Guid.Parse("E73B777D-CD5C-4E71-957A-B86B3660B7CF");
-
- /// <inheritdoc />
- public string Name => nameof(RenameEnableGroupingIntoCollections);
-
- /// <inheritdoc />
- public bool PerformOnNewInstall => false;
-
- /// <inheritdoc />
public void Perform()
{
string path = Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "system.xml");
diff --git a/Jellyfin.Server/Migrations/Routines/AddDefaultCastReceivers.cs b/Jellyfin.Server/Migrations/Routines/AddDefaultCastReceivers.cs
index 2047ec743..00d152b4b 100644
--- a/Jellyfin.Server/Migrations/Routines/AddDefaultCastReceivers.cs
+++ b/Jellyfin.Server/Migrations/Routines/AddDefaultCastReceivers.cs
@@ -7,7 +7,10 @@ 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
{
private readonly IServerConfigurationManager _serverConfigurationManager;
@@ -21,15 +24,6 @@ public class AddDefaultCastReceivers : IMigrationRoutine
}
/// <inheritdoc />
- public Guid Id => new("34A1A1C4-5572-418E-A2F8-32CDFE2668E8");
-
- /// <inheritdoc />
- public string Name => "AddDefaultCastReceivers";
-
- /// <inheritdoc />
- public bool PerformOnNewInstall => true;
-
- /// <inheritdoc />
public void Perform()
{
_serverConfigurationManager.Configuration.CastReceiverApplications =
diff --git a/Jellyfin.Server/Migrations/Routines/AddDefaultPluginRepository.cs b/Jellyfin.Server/Migrations/Routines/AddDefaultPluginRepository.cs
index fc6b5d597..8c8398a16 100644
--- a/Jellyfin.Server/Migrations/Routines/AddDefaultPluginRepository.cs
+++ b/Jellyfin.Server/Migrations/Routines/AddDefaultPluginRepository.cs
@@ -7,7 +7,10 @@ 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
{
private readonly IServerConfigurationManager _serverConfigurationManager;
@@ -27,15 +30,6 @@ namespace Jellyfin.Server.Migrations.Routines
}
/// <inheritdoc/>
- public Guid Id => Guid.Parse("EB58EBEE-9514-4B9B-8225-12E1A40020DF");
-
- /// <inheritdoc/>
- public string Name => "AddDefaultPluginRepository";
-
- /// <inheritdoc/>
- public bool PerformOnNewInstall => true;
-
- /// <inheritdoc/>
public void Perform()
{
_serverConfigurationManager.Configuration.PluginRepositories = new[] { _defaultRepositoryInfo };
diff --git a/Jellyfin.Server/Migrations/Routines/CreateUserLoggingConfigFile.cs b/Jellyfin.Server/Migrations/Routines/CreateUserLoggingConfigFile.cs
index 5a8ef2e1c..1326a6dc8 100644
--- a/Jellyfin.Server/Migrations/Routines/CreateUserLoggingConfigFile.cs
+++ b/Jellyfin.Server/Migrations/Routines/CreateUserLoggingConfigFile.cs
@@ -12,7 +12,10 @@ 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
{
/// <summary>
/// File history for logging.json as existed during this migration creation. The contents for each has been minified.
@@ -43,15 +46,6 @@ namespace Jellyfin.Server.Migrations.Routines
}
/// <inheritdoc/>
- public Guid Id => Guid.Parse("{EF103419-8451-40D8-9F34-D1A8E93A1679}");
-
- /// <inheritdoc/>
- public string Name => "CreateLoggingConfigHierarchy";
-
- /// <inheritdoc/>
- public bool PerformOnNewInstall => false;
-
- /// <inheritdoc/>
public void Perform()
{
var logDirectory = _appPaths.ConfigurationDirectoryPath;
diff --git a/Jellyfin.Server/Migrations/Routines/DisableTranscodingThrottling.cs b/Jellyfin.Server/Migrations/Routines/DisableTranscodingThrottling.cs
index 378e88e25..acf2835fe 100644
--- a/Jellyfin.Server/Migrations/Routines/DisableTranscodingThrottling.cs
+++ b/Jellyfin.Server/Migrations/Routines/DisableTranscodingThrottling.cs
@@ -7,7 +7,10 @@ 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
{
private readonly ILogger<DisableTranscodingThrottling> _logger;
private readonly IConfigurationManager _configManager;
@@ -19,15 +22,6 @@ namespace Jellyfin.Server.Migrations.Routines
}
/// <inheritdoc/>
- public Guid Id => Guid.Parse("{4124C2CD-E939-4FFB-9BE9-9B311C413638}");
-
- /// <inheritdoc/>
- public string Name => "DisableTranscodingThrottling";
-
- /// <inheritdoc/>
- public bool PerformOnNewInstall => false;
-
- /// <inheritdoc/>
public void Perform()
{
// Set EnableThrottling to false since it wasn't used before and may introduce issues
diff --git a/Jellyfin.Server/Migrations/Routines/FixAudioData.cs b/Jellyfin.Server/Migrations/Routines/FixAudioData.cs
index a20253369..05ded06ba 100644
--- a/Jellyfin.Server/Migrations/Routines/FixAudioData.cs
+++ b/Jellyfin.Server/Migrations/Routines/FixAudioData.cs
@@ -16,9 +16,12 @@ 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
{
- private const string DbFilename = "library.db";
private readonly ILogger<FixAudioData> _logger;
private readonly IServerApplicationPaths _applicationPaths;
private readonly IItemRepository _itemRepository;
@@ -34,40 +37,8 @@ namespace Jellyfin.Server.Migrations.Routines
}
/// <inheritdoc/>
- public Guid Id => Guid.Parse("{CF6FABC2-9FBE-4933-84A5-FFE52EF22A58}");
-
- /// <inheritdoc/>
- public string Name => "FixAudioData";
-
- /// <inheritdoc/>
- public bool PerformOnNewInstall => false;
-
- /// <inheritdoc/>
public void Perform()
{
- var dbPath = Path.Combine(_applicationPaths.DataPath, DbFilename);
-
- // Back up the database before modifying any entries
- for (int i = 1; ; i++)
- {
- var bakPath = string.Format(CultureInfo.InvariantCulture, "{0}.bak{1}", dbPath, i);
- if (!File.Exists(bakPath))
- {
- try
- {
- _logger.LogInformation("Backing up {Library} to {BackupPath}", DbFilename, bakPath);
- File.Copy(dbPath, bakPath);
- _logger.LogInformation("{Library} backed up to {BackupPath}", DbFilename, bakPath);
- break;
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Cannot make a backup of {Library} at path {BackupPath}", DbFilename, bakPath);
- throw;
- }
- }
- }
-
_logger.LogInformation("Backfilling audio lyrics data to database.");
var startIndex = 0;
var records = _itemRepository.GetCount(new InternalItemsQuery
diff --git a/Jellyfin.Server/Migrations/Routines/FixPlaylistOwner.cs b/Jellyfin.Server/Migrations/Routines/FixPlaylistOwner.cs
index 192c170b2..56614ece3 100644
--- a/Jellyfin.Server/Migrations/Routines/FixPlaylistOwner.cs
+++ b/Jellyfin.Server/Migrations/Routines/FixPlaylistOwner.cs
@@ -13,7 +13,10 @@ 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
{
private readonly ILogger<FixPlaylistOwner> _logger;
private readonly ILibraryManager _libraryManager;
@@ -30,15 +33,6 @@ internal class FixPlaylistOwner : IMigrationRoutine
}
/// <inheritdoc/>
- public Guid Id => Guid.Parse("{615DFA9E-2497-4DBB-A472-61938B752C5B}");
-
- /// <inheritdoc/>
- public string Name => "FixPlaylistOwner";
-
- /// <inheritdoc/>
- public bool PerformOnNewInstall => false;
-
- /// <inheritdoc/>
public void Perform()
{
var playlists = _libraryManager.GetItemList(new InternalItemsQuery
diff --git a/Jellyfin.Server/Migrations/Routines/MigrateActivityLogDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateActivityLogDb.cs
index e9fe9abce..a954d307e 100644
--- a/Jellyfin.Server/Migrations/Routines/MigrateActivityLogDb.cs
+++ b/Jellyfin.Server/Migrations/Routines/MigrateActivityLogDb.cs
@@ -14,7 +14,10 @@ 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
{
private const string DbFilename = "activitylog.db";
@@ -36,15 +39,6 @@ namespace Jellyfin.Server.Migrations.Routines
}
/// <inheritdoc/>
- public Guid Id => Guid.Parse("3793eb59-bc8c-456c-8b9f-bd5a62a42978");
-
- /// <inheritdoc/>
- public string Name => "MigrateActivityLogDatabase";
-
- /// <inheritdoc/>
- public bool PerformOnNewInstall => false;
-
- /// <inheritdoc/>
public void Perform()
{
var logLevelDictionary = new Dictionary<string, LogLevel>(StringComparer.OrdinalIgnoreCase)
diff --git a/Jellyfin.Server/Migrations/Routines/MigrateAuthenticationDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateAuthenticationDb.cs
index feaf46c84..c6699c21d 100644
--- a/Jellyfin.Server/Migrations/Routines/MigrateAuthenticationDb.cs
+++ b/Jellyfin.Server/Migrations/Routines/MigrateAuthenticationDb.cs
@@ -15,7 +15,10 @@ 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
{
private const string DbFilename = "authentication.db";
@@ -44,15 +47,6 @@ namespace Jellyfin.Server.Migrations.Routines
}
/// <inheritdoc />
- public Guid Id => Guid.Parse("5BD72F41-E6F3-4F60-90AA-09869ABE0E22");
-
- /// <inheritdoc />
- public string Name => "MigrateAuthenticationDatabase";
-
- /// <inheritdoc />
- public bool PerformOnNewInstall => false;
-
- /// <inheritdoc />
public void Perform()
{
var dataPath = _appPaths.DataPath;
diff --git a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs
index a8fa2e52a..0d9952ce9 100644
--- a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs
+++ b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs
@@ -20,7 +20,10 @@ 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
{
private const string DbFilename = "displaypreferences.db";
@@ -52,15 +55,6 @@ namespace Jellyfin.Server.Migrations.Routines
}
/// <inheritdoc />
- public Guid Id => Guid.Parse("06387815-C3CC-421F-A888-FB5F9992BEA8");
-
- /// <inheritdoc />
- public string Name => "MigrateDisplayPreferencesDatabase";
-
- /// <inheritdoc />
- public bool PerformOnNewInstall => false;
-
- /// <inheritdoc />
public void Perform()
{
HomeSectionType[] defaults =
diff --git a/Jellyfin.Server/Migrations/Routines/MigrateKeyframeData.cs b/Jellyfin.Server/Migrations/Routines/MigrateKeyframeData.cs
new file mode 100644
index 000000000..033045e63
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Routines/MigrateKeyframeData.cs
@@ -0,0 +1,152 @@
+using System;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text.Json;
+using Jellyfin.Data.Enums;
+using Jellyfin.Database.Implementations;
+using Jellyfin.Database.Implementations.Entities;
+using Jellyfin.Extensions.Json;
+using Jellyfin.Server.ServerSetupApp;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Extensions;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Migrations.Routines;
+
+/// <summary>
+/// Migration to move extracted files to the new directories.
+/// </summary>
+[JellyfinMigration("2025-04-21T00:00:00", nameof(MigrateKeyframeData))]
+public class MigrateKeyframeData : IDatabaseMigrationRoutine
+{
+ private readonly IStartupLogger _logger;
+ private readonly IApplicationPaths _appPaths;
+ private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
+ private static readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MigrateKeyframeData"/> class.
+ /// </summary>
+ /// <param name="startupLogger">The startup logger for Startup UI intigration.</param>
+ /// <param name="appPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
+ /// <param name="dbProvider">The EFCore db factory.</param>
+ public MigrateKeyframeData(
+ IStartupLogger startupLogger,
+ IApplicationPaths appPaths,
+ IDbContextFactory<JellyfinDbContext> dbProvider)
+ {
+ _logger = startupLogger;
+ _appPaths = appPaths;
+ _dbProvider = dbProvider;
+ }
+
+ private string KeyframeCachePath => Path.Combine(_appPaths.DataPath, "keyframes");
+
+ /// <inheritdoc />
+ public void Perform()
+ {
+ const int Limit = 5000;
+ int itemCount = 0, offset = 0;
+
+ var sw = Stopwatch.StartNew();
+
+ using var context = _dbProvider.CreateDbContext();
+ var baseQuery = context.BaseItems.Where(b => b.MediaType == MediaType.Video.ToString() && !b.IsVirtualItem && !b.IsFolder).OrderBy(e => e.Id);
+ var records = baseQuery.Count();
+ _logger.LogInformation("Checking {Count} items for importable keyframe data.", records);
+
+ context.KeyframeData.ExecuteDelete();
+ using var transaction = context.Database.BeginTransaction();
+ do
+ {
+ var results = baseQuery.Skip(offset).Take(Limit).Select(b => new Tuple<Guid, string?>(b.Id, b.Path)).ToList();
+ foreach (var result in results)
+ {
+ if (TryGetKeyframeData(result.Item1, result.Item2, out var data))
+ {
+ itemCount++;
+ context.KeyframeData.Add(data);
+ }
+ }
+
+ offset += Limit;
+ if (offset > records)
+ {
+ offset = records;
+ }
+
+ _logger.LogInformation("Checked: {Count} - Imported: {Items} - Time: {Time}", offset, itemCount, sw.Elapsed);
+ } while (offset < records);
+
+ context.SaveChanges();
+ transaction.Commit();
+
+ _logger.LogInformation("Imported keyframes for {Count} items in {Time}", itemCount, sw.Elapsed);
+
+ if (Directory.Exists(KeyframeCachePath))
+ {
+ Directory.Delete(KeyframeCachePath, true);
+ }
+ }
+
+ private bool TryGetKeyframeData(Guid id, string? path, [NotNullWhen(true)] out KeyframeData? data)
+ {
+ data = null;
+ if (!string.IsNullOrEmpty(path))
+ {
+ var cachePath = GetCachePath(KeyframeCachePath, path);
+ if (TryReadFromCache(cachePath, out var keyframeData))
+ {
+ data = new()
+ {
+ ItemId = id,
+ KeyframeTicks = keyframeData.KeyframeTicks.ToList(),
+ TotalDuration = keyframeData.TotalDuration
+ };
+
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private string? GetCachePath(string keyframeCachePath, string filePath)
+ {
+ DateTime? lastWriteTimeUtc;
+ try
+ {
+ lastWriteTimeUtc = File.GetLastWriteTimeUtc(filePath);
+ }
+ catch (IOException e)
+ {
+ _logger.LogDebug("Skipping {Path}: {Exception}", filePath, e.Message);
+
+ return null;
+ }
+
+ ReadOnlySpan<char> filename = (filePath + "_" + lastWriteTimeUtc.Value.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5() + ".json";
+ var prefix = filename[..1];
+
+ return Path.Join(keyframeCachePath, prefix, filename);
+ }
+
+ private static bool TryReadFromCache(string? cachePath, [NotNullWhen(true)] out MediaEncoding.Keyframes.KeyframeData? cachedResult)
+ {
+ if (File.Exists(cachePath))
+ {
+ var bytes = File.ReadAllBytes(cachePath);
+ cachedResult = JsonSerializer.Deserialize<MediaEncoding.Keyframes.KeyframeData>(bytes, _jsonOptions);
+
+ return cachedResult is not null;
+ }
+
+ cachedResult = null;
+
+ return false;
+ }
+}
diff --git a/Jellyfin.Server/Migrations/Routines/MigrateLibraryDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateLibraryDb.cs
index 427f04f9d..521655a4f 100644
--- a/Jellyfin.Server/Migrations/Routines/MigrateLibraryDb.cs
+++ b/Jellyfin.Server/Migrations/Routines/MigrateLibraryDb.cs
@@ -9,12 +9,12 @@ using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
-using System.Threading;
using Emby.Server.Implementations.Data;
using Jellyfin.Database.Implementations;
using Jellyfin.Database.Implementations.Entities;
using Jellyfin.Extensions;
using Jellyfin.Server.Implementations.Item;
+using Jellyfin.Server.ServerSetupApp;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Entities;
@@ -29,11 +29,13 @@ namespace Jellyfin.Server.Migrations.Routines;
/// <summary>
/// The migration routine for migrating the userdata database to EF Core.
/// </summary>
+[JellyfinMigration("2025-04-20T20:00:00", nameof(MigrateLibraryDb))]
+[JellyfinMigrationBackup(JellyfinDb = true, LegacyLibraryDb = true)]
internal class MigrateLibraryDb : IDatabaseMigrationRoutine
{
private const string DbFilename = "library.db";
- private readonly ILogger<MigrateLibraryDb> _logger;
+ private readonly IStartupLogger _logger;
private readonly IServerApplicationPaths _paths;
private readonly IJellyfinDatabaseProvider _jellyfinDatabaseProvider;
private readonly IDbContextFactory<JellyfinDbContext> _provider;
@@ -41,305 +43,379 @@ internal class MigrateLibraryDb : IDatabaseMigrationRoutine
/// <summary>
/// Initializes a new instance of the <see cref="MigrateLibraryDb"/> class.
/// </summary>
- /// <param name="logger">The logger.</param>
+ /// <param name="startupLogger">The startup logger for Startup UI intigration.</param>
/// <param name="provider">The database provider.</param>
/// <param name="paths">The server application paths.</param>
/// <param name="jellyfinDatabaseProvider">The database provider for special access.</param>
public MigrateLibraryDb(
- ILogger<MigrateLibraryDb> logger,
+ IStartupLogger startupLogger,
IDbContextFactory<JellyfinDbContext> provider,
IServerApplicationPaths paths,
IJellyfinDatabaseProvider jellyfinDatabaseProvider)
{
- _logger = logger;
+ _logger = startupLogger;
_provider = provider;
_paths = paths;
_jellyfinDatabaseProvider = jellyfinDatabaseProvider;
}
/// <inheritdoc/>
- public Guid Id => Guid.Parse("36445464-849f-429f-9ad0-bb130efa0664");
-
- /// <inheritdoc/>
- public string Name => "MigrateLibraryDbData";
-
- /// <inheritdoc/>
- public bool PerformOnNewInstall => false; // TODO Change back after testing
-
- /// <inheritdoc/>
public void Perform()
{
_logger.LogInformation("Migrating the userdata from library.db may take a while, do not stop Jellyfin.");
var dataPath = _paths.DataPath;
var libraryDbPath = Path.Combine(dataPath, DbFilename);
- using var connection = new SqliteConnection($"Filename={libraryDbPath}");
- var migrationTotalTime = TimeSpan.Zero;
+ if (!File.Exists(libraryDbPath))
+ {
+ _logger.LogError("Cannot migrate {LibraryDb} as it does not exist..", libraryDbPath);
+ return;
+ }
- var stopwatch = new Stopwatch();
- stopwatch.Start();
+ using var connection = new SqliteConnection($"Filename={libraryDbPath};Mode=ReadOnly");
- connection.Open();
- using var dbContext = _provider.CreateDbContext();
-
- migrationTotalTime += stopwatch.Elapsed;
- _logger.LogInformation("Saving UserData entries took {0}.", stopwatch.Elapsed);
- stopwatch.Restart();
-
- _logger.LogInformation("Start moving TypedBaseItem.");
- const string typedBaseItemsQuery = """
- SELECT guid, type, data, StartDate, EndDate, ChannelId, IsMovie,
- IsSeries, EpisodeTitle, IsRepeat, CommunityRating, CustomRating, IndexNumber, IsLocked, PreferredMetadataLanguage,
- PreferredMetadataCountryCode, Width, Height, DateLastRefreshed, Name, Path, PremiereDate, Overview, ParentIndexNumber,
- ProductionYear, OfficialRating, ForcedSortName, RunTimeTicks, Size, DateCreated, DateModified, Genres, ParentId, TopParentId,
- Audio, ExternalServiceId, IsInMixedFolder, DateLastSaved, LockedFields, Studios, Tags, TrailerTypes, OriginalTitle, PrimaryVersionId,
- DateLastMediaAdded, Album, LUFS, NormalizationGain, CriticRating, IsVirtualItem, SeriesName, UserDataKey, SeasonName, SeasonId, SeriesId,
- PresentationUniqueKey, InheritedParentalRatingValue, ExternalSeriesId, Tagline, ProviderIds, Images, ProductionLocations, ExtraIds, TotalBitrate,
- ExtraType, Artists, AlbumArtists, ExternalId, SeriesPresentationUniqueKey, ShowId, OwnerId, MediaType, SortName, CleanName, UnratedType FROM TypedBaseItems
- """;
- dbContext.BaseItems.ExecuteDelete();
+ var fullOperationTimer = new Stopwatch();
+ fullOperationTimer.Start();
- var legacyBaseItemWithUserKeys = new Dictionary<string, BaseItemEntity>();
- foreach (SqliteDataReader dto in connection.Query(typedBaseItemsQuery))
+ using (var operation = GetPreparedDbContext("Cleanup database"))
{
- var baseItem = GetItem(dto);
- dbContext.BaseItems.Add(baseItem.BaseItem);
- foreach (var dataKey in baseItem.LegacyUserDataKey)
- {
- legacyBaseItemWithUserKeys[dataKey] = baseItem.BaseItem;
- }
+ operation.JellyfinDbContext.AttachmentStreamInfos.ExecuteDelete();
+ operation.JellyfinDbContext.BaseItems.ExecuteDelete();
+ operation.JellyfinDbContext.ItemValues.ExecuteDelete();
+ operation.JellyfinDbContext.UserData.ExecuteDelete();
+ operation.JellyfinDbContext.MediaStreamInfos.ExecuteDelete();
+ operation.JellyfinDbContext.Peoples.ExecuteDelete();
+ operation.JellyfinDbContext.PeopleBaseItemMap.ExecuteDelete();
+ operation.JellyfinDbContext.Chapters.ExecuteDelete();
+ operation.JellyfinDbContext.AncestorIds.ExecuteDelete();
}
- _logger.LogInformation("Try saving {0} BaseItem entries.", dbContext.BaseItems.Local.Count);
- dbContext.SaveChanges();
- migrationTotalTime += stopwatch.Elapsed;
- _logger.LogInformation("Saving BaseItems entries took {0}.", stopwatch.Elapsed);
- stopwatch.Restart();
+ var legacyBaseItemWithUserKeys = new Dictionary<string, BaseItemEntity>();
+ connection.Open();
- _logger.LogInformation("Start moving ItemValues.");
- // do not migrate inherited types as they are now properly mapped in search and lookup.
- const string itemValueQuery =
- """
- SELECT ItemId, Type, Value, CleanValue FROM ItemValues
- WHERE Type <> 6 AND EXISTS(SELECT 1 FROM TypedBaseItems WHERE TypedBaseItems.guid = ItemValues.ItemId)
- """;
- dbContext.ItemValues.ExecuteDelete();
+ var baseItemIds = new HashSet<Guid>();
+ using (var operation = GetPreparedDbContext("moving TypedBaseItem"))
+ {
+ const string typedBaseItemsQuery =
+ """
+ SELECT guid, type, data, StartDate, EndDate, ChannelId, IsMovie,
+ IsSeries, EpisodeTitle, IsRepeat, CommunityRating, CustomRating, IndexNumber, IsLocked, PreferredMetadataLanguage,
+ PreferredMetadataCountryCode, Width, Height, DateLastRefreshed, Name, Path, PremiereDate, Overview, ParentIndexNumber,
+ ProductionYear, OfficialRating, ForcedSortName, RunTimeTicks, Size, DateCreated, DateModified, Genres, ParentId, TopParentId,
+ Audio, ExternalServiceId, IsInMixedFolder, DateLastSaved, LockedFields, Studios, Tags, TrailerTypes, OriginalTitle, PrimaryVersionId,
+ DateLastMediaAdded, Album, LUFS, NormalizationGain, CriticRating, IsVirtualItem, SeriesName, UserDataKey, SeasonName, SeasonId, SeriesId,
+ PresentationUniqueKey, InheritedParentalRatingValue, ExternalSeriesId, Tagline, ProviderIds, Images, ProductionLocations, ExtraIds, TotalBitrate,
+ ExtraType, Artists, AlbumArtists, ExternalId, SeriesPresentationUniqueKey, ShowId, OwnerId, MediaType, SortName, CleanName, UnratedType FROM TypedBaseItems
+ """;
+ using (new TrackedMigrationStep("Loading TypedBaseItems", _logger))
+ {
+ foreach (SqliteDataReader dto in connection.Query(typedBaseItemsQuery))
+ {
+ var baseItem = GetItem(dto);
+ operation.JellyfinDbContext.BaseItems.Add(baseItem.BaseItem);
+ baseItemIds.Add(baseItem.BaseItem.Id);
+ foreach (var dataKey in baseItem.LegacyUserDataKey)
+ {
+ legacyBaseItemWithUserKeys[dataKey] = baseItem.BaseItem;
+ }
+ }
+ }
- // EFCores local lookup sucks. We cannot use context.ItemValues.Local here because its just super slow.
- var localItems = new Dictionary<(int Type, string CleanValue), (Database.Implementations.Entities.ItemValue ItemValue, List<Guid> ItemIds)>();
+ using (new TrackedMigrationStep($"saving {operation.JellyfinDbContext.BaseItems.Local.Count} BaseItem entries", _logger))
+ {
+ operation.JellyfinDbContext.SaveChanges();
+ }
+ }
- foreach (SqliteDataReader dto in connection.Query(itemValueQuery))
+ using (var operation = GetPreparedDbContext("moving ItemValues"))
{
- var itemId = dto.GetGuid(0);
- var entity = GetItemValue(dto);
- var key = ((int)entity.Type, entity.CleanValue);
- if (!localItems.TryGetValue(key, out var existing))
+ // do not migrate inherited types as they are now properly mapped in search and lookup.
+ const string itemValueQuery =
+ """
+ SELECT ItemId, Type, Value, CleanValue FROM ItemValues
+ WHERE Type <> 6 AND EXISTS(SELECT 1 FROM TypedBaseItems WHERE TypedBaseItems.guid = ItemValues.ItemId)
+ """;
+
+ // EFCores local lookup sucks. We cannot use context.ItemValues.Local here because its just super slow.
+ var localItems = new Dictionary<(int Type, string Value), (Database.Implementations.Entities.ItemValue ItemValue, List<Guid> ItemIds)>();
+ using (new TrackedMigrationStep("loading ItemValues", _logger))
{
- localItems[key] = existing = (entity, []);
+ foreach (SqliteDataReader dto in connection.Query(itemValueQuery))
+ {
+ var itemId = dto.GetGuid(0);
+ var entity = GetItemValue(dto);
+ var key = ((int)entity.Type, entity.Value);
+ if (!localItems.TryGetValue(key, out var existing))
+ {
+ localItems[key] = existing = (entity, []);
+ }
+
+ existing.ItemIds.Add(itemId);
+ }
+
+ foreach (var item in localItems)
+ {
+ operation.JellyfinDbContext.ItemValues.Add(item.Value.ItemValue);
+ operation.JellyfinDbContext.ItemValuesMap.AddRange(item.Value.ItemIds.Distinct().Select(f => new ItemValueMap()
+ {
+ Item = null!,
+ ItemValue = null!,
+ ItemId = f,
+ ItemValueId = item.Value.ItemValue.ItemValueId
+ }));
+ }
}
- existing.ItemIds.Add(itemId);
+ using (new TrackedMigrationStep($"saving {operation.JellyfinDbContext.ItemValues.Local.Count} ItemValues entries", _logger))
+ {
+ operation.JellyfinDbContext.SaveChanges();
+ }
}
- foreach (var item in localItems)
+ using (var operation = GetPreparedDbContext("moving UserData"))
{
- dbContext.ItemValues.Add(item.Value.ItemValue);
- dbContext.ItemValuesMap.AddRange(item.Value.ItemIds.Distinct().Select(f => new ItemValueMap()
+ var queryResult = connection.Query(
+ """
+ SELECT key, userId, rating, played, playCount, isFavorite, playbackPositionTicks, lastPlayedDate, AudioStreamIndex, SubtitleStreamIndex FROM UserDatas
+
+ WHERE EXISTS(SELECT 1 FROM TypedBaseItems WHERE TypedBaseItems.UserDataKey = UserDatas.key)
+ """);
+
+ using (new TrackedMigrationStep("loading UserData", _logger))
{
- Item = null!,
- ItemValue = null!,
- ItemId = f,
- ItemValueId = item.Value.ItemValue.ItemValueId
- }));
- }
+ var users = operation.JellyfinDbContext.Users.AsNoTracking().ToImmutableArray();
+ var userIdBlacklist = new HashSet<int>();
- _logger.LogInformation("Try saving {0} ItemValues entries.", dbContext.ItemValues.Local.Count);
- dbContext.SaveChanges();
- migrationTotalTime += stopwatch.Elapsed;
- _logger.LogInformation("Saving People ItemValues took {0}.", stopwatch.Elapsed);
- stopwatch.Restart();
+ foreach (var entity in queryResult)
+ {
+ var userData = GetUserData(users, entity, userIdBlacklist);
+ if (userData is null)
+ {
+ var userDataId = entity.GetString(0);
+ var internalUserId = entity.GetInt32(1);
- _logger.LogInformation("Start moving UserData.");
- var queryResult = connection.Query("""
- SELECT key, userId, rating, played, playCount, isFavorite, playbackPositionTicks, lastPlayedDate, AudioStreamIndex, SubtitleStreamIndex FROM UserDatas
+ if (!userIdBlacklist.Contains(internalUserId))
+ {
+ _logger.LogError("Was not able to migrate user data with key {0} because its id {InternalId} does not match any existing user.", userDataId, internalUserId);
+ userIdBlacklist.Add(internalUserId);
+ }
- WHERE EXISTS(SELECT 1 FROM TypedBaseItems WHERE TypedBaseItems.UserDataKey = UserDatas.key)
- """);
+ continue;
+ }
- dbContext.UserData.ExecuteDelete();
+ if (!legacyBaseItemWithUserKeys.TryGetValue(userData.CustomDataKey!, out var refItem))
+ {
+ _logger.LogError("Was not able to migrate user data with key {0} because it does not reference a valid BaseItem.", entity.GetString(0));
+ continue;
+ }
- var users = dbContext.Users.AsNoTracking().ToImmutableArray();
+ userData.ItemId = refItem.Id;
+ operation.JellyfinDbContext.UserData.Add(userData);
+ }
- foreach (var entity in queryResult)
- {
- var userData = GetUserData(users, entity);
- if (userData is null)
- {
- _logger.LogError("Was not able to migrate user data with key {0}", entity.GetString(0));
- continue;
+ users.Clear();
}
- if (!legacyBaseItemWithUserKeys.TryGetValue(userData.CustomDataKey!, out var refItem))
+ legacyBaseItemWithUserKeys.Clear();
+
+ using (new TrackedMigrationStep($"saving {operation.JellyfinDbContext.UserData.Local.Count} UserData entries", _logger))
{
- _logger.LogError("Was not able to migrate user data with key {0} because it does not reference a valid BaseItem.", entity.GetString(0));
- continue;
+ operation.JellyfinDbContext.SaveChanges();
}
-
- userData.ItemId = refItem.Id;
- dbContext.UserData.Add(userData);
}
- users.Clear();
- legacyBaseItemWithUserKeys.Clear();
- _logger.LogInformation("Try saving {0} UserData entries.", dbContext.UserData.Local.Count);
- dbContext.SaveChanges();
-
- _logger.LogInformation("Start moving MediaStreamInfos.");
- const string mediaStreamQuery = """
- SELECT ItemId, StreamIndex, StreamType, Codec, Language, ChannelLayout, Profile, AspectRatio, Path,
- IsInterlaced, BitRate, Channels, SampleRate, IsDefault, IsForced, IsExternal, Height, Width,
- AverageFrameRate, RealFrameRate, Level, PixelFormat, BitDepth, IsAnamorphic, RefFrames, CodecTag,
- Comment, NalLengthSize, IsAvc, Title, TimeBase, CodecTimeBase, ColorPrimaries, ColorSpace, ColorTransfer,
- DvVersionMajor, DvVersionMinor, DvProfile, DvLevel, RpuPresentFlag, ElPresentFlag, BlPresentFlag, DvBlSignalCompatibilityId, IsHearingImpaired
- FROM MediaStreams
- WHERE EXISTS(SELECT 1 FROM TypedBaseItems WHERE TypedBaseItems.guid = MediaStreams.ItemId)
- """;
- dbContext.MediaStreamInfos.ExecuteDelete();
-
- foreach (SqliteDataReader dto in connection.Query(mediaStreamQuery))
+ using (var operation = GetPreparedDbContext("moving MediaStreamInfos"))
{
- dbContext.MediaStreamInfos.Add(GetMediaStream(dto));
- }
+ const string mediaStreamQuery =
+ """
+ SELECT ItemId, StreamIndex, StreamType, Codec, Language, ChannelLayout, Profile, AspectRatio, Path,
+ IsInterlaced, BitRate, Channels, SampleRate, IsDefault, IsForced, IsExternal, Height, Width,
+ AverageFrameRate, RealFrameRate, Level, PixelFormat, BitDepth, IsAnamorphic, RefFrames, CodecTag,
+ Comment, NalLengthSize, IsAvc, Title, TimeBase, CodecTimeBase, ColorPrimaries, ColorSpace, ColorTransfer,
+ DvVersionMajor, DvVersionMinor, DvProfile, DvLevel, RpuPresentFlag, ElPresentFlag, BlPresentFlag, DvBlSignalCompatibilityId, IsHearingImpaired
+ FROM MediaStreams
+ WHERE EXISTS(SELECT 1 FROM TypedBaseItems WHERE TypedBaseItems.guid = MediaStreams.ItemId)
+ """;
- _logger.LogInformation("Try saving {0} MediaStreamInfos entries.", dbContext.MediaStreamInfos.Local.Count);
- dbContext.SaveChanges();
-
- migrationTotalTime += stopwatch.Elapsed;
- _logger.LogInformation("Saving MediaStreamInfos entries took {0}.", stopwatch.Elapsed);
- stopwatch.Restart();
-
- _logger.LogInformation("Start moving People.");
- const string personsQuery = """
- SELECT ItemId, Name, Role, PersonType, SortOrder FROM People
- WHERE EXISTS(SELECT 1 FROM TypedBaseItems WHERE TypedBaseItems.guid = People.ItemId)
- """;
- dbContext.Peoples.ExecuteDelete();
- dbContext.PeopleBaseItemMap.ExecuteDelete();
-
- var peopleCache = new Dictionary<string, (People Person, List<PeopleBaseItemMap> Items)>();
- var baseItemIds = dbContext.BaseItems.Select(b => b.Id).ToHashSet();
+ using (new TrackedMigrationStep("loading MediaStreamInfos", _logger))
+ {
+ foreach (SqliteDataReader dto in connection.Query(mediaStreamQuery))
+ {
+ operation.JellyfinDbContext.MediaStreamInfos.Add(GetMediaStream(dto));
+ }
+ }
- foreach (SqliteDataReader reader in connection.Query(personsQuery))
- {
- var itemId = reader.GetGuid(0);
- if (!baseItemIds.Contains(itemId))
+ using (new TrackedMigrationStep($"saving {operation.JellyfinDbContext.MediaStreamInfos.Local.Count} MediaStreamInfos entries", _logger))
{
- _logger.LogError("Dont save person {0} because its not in use by any BaseItem", reader.GetString(1));
- continue;
+ operation.JellyfinDbContext.SaveChanges();
}
+ }
+
+ using (var operation = GetPreparedDbContext("moving AttachmentStreamInfos"))
+ {
+ const string mediaAttachmentQuery =
+ """
+ SELECT ItemId, AttachmentIndex, Codec, CodecTag, Comment, filename, MIMEType
+ FROM mediaattachments
+ WHERE EXISTS(SELECT 1 FROM TypedBaseItems WHERE TypedBaseItems.guid = mediaattachments.ItemId)
+ """;
- var entity = GetPerson(reader);
- if (!peopleCache.TryGetValue(entity.Name, out var personCache))
+ using (new TrackedMigrationStep("loading AttachmentStreamInfos", _logger))
{
- peopleCache[entity.Name] = personCache = (entity, []);
+ foreach (SqliteDataReader dto in connection.Query(mediaAttachmentQuery))
+ {
+ operation.JellyfinDbContext.AttachmentStreamInfos.Add(GetMediaAttachment(dto));
+ }
}
- if (reader.TryGetString(2, out var role))
+ using (new TrackedMigrationStep($"saving {operation.JellyfinDbContext.AttachmentStreamInfos.Local.Count} AttachmentStreamInfos entries", _logger))
{
+ operation.JellyfinDbContext.SaveChanges();
}
+ }
- int? sortOrder = reader.IsDBNull(4) ? null : reader.GetInt32(4);
+ using (var operation = GetPreparedDbContext("moving People"))
+ {
+ const string personsQuery =
+ """
+ SELECT ItemId, Name, Role, PersonType, SortOrder FROM People
+ WHERE EXISTS(SELECT 1 FROM TypedBaseItems WHERE TypedBaseItems.guid = People.ItemId)
+ """;
- personCache.Items.Add(new PeopleBaseItemMap()
+ var peopleCache = new Dictionary<string, (People Person, List<PeopleBaseItemMap> Items)>();
+
+ using (new TrackedMigrationStep("loading People", _logger))
{
- Item = null!,
- ItemId = itemId,
- People = null!,
- PeopleId = personCache.Person.Id,
- ListOrder = sortOrder,
- SortOrder = sortOrder,
- Role = role
- });
- }
+ foreach (SqliteDataReader reader in connection.Query(personsQuery))
+ {
+ var itemId = reader.GetGuid(0);
+ if (!baseItemIds.Contains(itemId))
+ {
+ _logger.LogError("Dont save person {0} because its not in use by any BaseItem", reader.GetString(1));
+ continue;
+ }
- baseItemIds.Clear();
+ var entity = GetPerson(reader);
+ if (!peopleCache.TryGetValue(entity.Name, out var personCache))
+ {
+ peopleCache[entity.Name] = personCache = (entity, []);
+ }
- foreach (var item in peopleCache)
- {
- dbContext.Peoples.Add(item.Value.Person);
- dbContext.PeopleBaseItemMap.AddRange(item.Value.Items.DistinctBy(e => (e.ItemId, e.PeopleId)));
- }
+ if (reader.TryGetString(2, out var role))
+ {
+ }
- peopleCache.Clear();
+ int? sortOrder = reader.IsDBNull(4) ? null : reader.GetInt32(4);
- _logger.LogInformation("Try saving {0} People entries.", dbContext.MediaStreamInfos.Local.Count);
- dbContext.SaveChanges();
- migrationTotalTime += stopwatch.Elapsed;
- _logger.LogInformation("Saving People entries took {0}.", stopwatch.Elapsed);
- stopwatch.Restart();
+ personCache.Items.Add(new PeopleBaseItemMap()
+ {
+ Item = null!,
+ ItemId = itemId,
+ People = null!,
+ PeopleId = personCache.Person.Id,
+ ListOrder = sortOrder,
+ SortOrder = sortOrder,
+ Role = role
+ });
+ }
- _logger.LogInformation("Start moving Chapters.");
- const string chapterQuery = """
- SELECT ItemId,StartPositionTicks,Name,ImagePath,ImageDateModified,ChapterIndex from Chapters2
- WHERE EXISTS(SELECT 1 FROM TypedBaseItems WHERE TypedBaseItems.guid = Chapters2.ItemId)
- """;
- dbContext.Chapters.ExecuteDelete();
+ baseItemIds.Clear();
- foreach (SqliteDataReader dto in connection.Query(chapterQuery))
- {
- var chapter = GetChapter(dto);
- dbContext.Chapters.Add(chapter);
- }
+ foreach (var item in peopleCache)
+ {
+ operation.JellyfinDbContext.Peoples.Add(item.Value.Person);
+ operation.JellyfinDbContext.PeopleBaseItemMap.AddRange(item.Value.Items.DistinctBy(e => (e.ItemId, e.PeopleId)));
+ }
- _logger.LogInformation("Try saving {0} Chapters entries.", dbContext.Chapters.Local.Count);
- dbContext.SaveChanges();
- migrationTotalTime += stopwatch.Elapsed;
- _logger.LogInformation("Saving Chapters took {0}.", stopwatch.Elapsed);
- stopwatch.Restart();
+ peopleCache.Clear();
+ }
- _logger.LogInformation("Start moving AncestorIds.");
- const string ancestorIdsQuery = """
- SELECT ItemId, AncestorId, AncestorIdText FROM AncestorIds
- WHERE
- EXISTS(SELECT 1 FROM TypedBaseItems WHERE TypedBaseItems.guid = AncestorIds.ItemId)
- AND
- EXISTS(SELECT 1 FROM TypedBaseItems WHERE TypedBaseItems.guid = AncestorIds.AncestorId)
- """;
- dbContext.Chapters.ExecuteDelete();
+ using (new TrackedMigrationStep($"saving {operation.JellyfinDbContext.Peoples.Local.Count} People entries and {operation.JellyfinDbContext.PeopleBaseItemMap.Local.Count} maps", _logger))
+ {
+ operation.JellyfinDbContext.SaveChanges();
+ }
+ }
- foreach (SqliteDataReader dto in connection.Query(ancestorIdsQuery))
+ using (var operation = GetPreparedDbContext("moving Chapters"))
{
- var ancestorId = GetAncestorId(dto);
- dbContext.AncestorIds.Add(ancestorId);
+ const string chapterQuery =
+ """
+ SELECT ItemId,StartPositionTicks,Name,ImagePath,ImageDateModified,ChapterIndex from Chapters2
+ WHERE EXISTS(SELECT 1 FROM TypedBaseItems WHERE TypedBaseItems.guid = Chapters2.ItemId)
+ """;
+
+ using (new TrackedMigrationStep("loading Chapters", _logger))
+ {
+ foreach (SqliteDataReader dto in connection.Query(chapterQuery))
+ {
+ var chapter = GetChapter(dto);
+ operation.JellyfinDbContext.Chapters.Add(chapter);
+ }
+ }
+
+ using (new TrackedMigrationStep($"saving {operation.JellyfinDbContext.Chapters.Local.Count} Chapters entries", _logger))
+ {
+ operation.JellyfinDbContext.SaveChanges();
+ }
}
- _logger.LogInformation("Try saving {0} AncestorIds entries.", dbContext.Chapters.Local.Count);
+ using (var operation = GetPreparedDbContext("moving AncestorIds"))
+ {
+ const string ancestorIdsQuery =
+ """
+ SELECT ItemId, AncestorId, AncestorIdText FROM AncestorIds
+ WHERE
+ EXISTS(SELECT 1 FROM TypedBaseItems WHERE TypedBaseItems.guid = AncestorIds.ItemId)
+ AND
+ EXISTS(SELECT 1 FROM TypedBaseItems WHERE TypedBaseItems.guid = AncestorIds.AncestorId)
+ """;
- dbContext.SaveChanges();
- migrationTotalTime += stopwatch.Elapsed;
- _logger.LogInformation("Saving AncestorIds took {0}.", stopwatch.Elapsed);
- stopwatch.Restart();
+ using (new TrackedMigrationStep("loading AncestorIds", _logger))
+ {
+ foreach (SqliteDataReader dto in connection.Query(ancestorIdsQuery))
+ {
+ var ancestorId = GetAncestorId(dto);
+ operation.JellyfinDbContext.AncestorIds.Add(ancestorId);
+ }
+ }
+
+ using (new TrackedMigrationStep($"saving {operation.JellyfinDbContext.AncestorIds.Local.Count} AncestorId entries", _logger))
+ {
+ operation.JellyfinDbContext.SaveChanges();
+ }
+ }
connection.Close();
+
_logger.LogInformation("Migration of the Library.db done.");
- _logger.LogInformation("Move {0} to {1}.", libraryDbPath, libraryDbPath + ".old");
+ _logger.LogInformation("Migrating Library db took {0}.", fullOperationTimer.Elapsed);
SqliteConnection.ClearAllPools();
+ _logger.LogInformation("Move {0} to {1}.", libraryDbPath, libraryDbPath + ".old");
File.Move(libraryDbPath, libraryDbPath + ".old", true);
+ }
- _logger.LogInformation("Migrating Library db took {0}.", migrationTotalTime);
-
- _jellyfinDatabaseProvider.RunScheduledOptimisation(CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
+ private DatabaseMigrationStep GetPreparedDbContext(string operationName)
+ {
+ var dbContext = _provider.CreateDbContext();
+ dbContext.ChangeTracker.AutoDetectChangesEnabled = false;
+ dbContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
+ return new DatabaseMigrationStep(dbContext, operationName, _logger);
}
- private UserData? GetUserData(ImmutableArray<User> users, SqliteDataReader dto)
+ private UserData? GetUserData(ImmutableArray<User> users, SqliteDataReader dto, HashSet<int> userIdBlacklist)
{
var internalUserId = dto.GetInt32(1);
var user = users.FirstOrDefault(e => e.InternalId == internalUserId);
if (user is null)
{
+ if (userIdBlacklist.Contains(internalUserId))
+ {
+ return null;
+ }
+
_logger.LogError("Tried to find user with index '{Idx}' but there are only '{MaxIdx}' users.", internalUserId, users.Length);
return null;
}
@@ -654,6 +730,48 @@ internal class MigrateLibraryDb : IDatabaseMigrationRoutine
return item;
}
+ /// <summary>
+ /// Gets the attachment.
+ /// </summary>
+ /// <param name="reader">The reader.</param>
+ /// <returns>MediaAttachment.</returns>
+ private AttachmentStreamInfo GetMediaAttachment(SqliteDataReader reader)
+ {
+ var item = new AttachmentStreamInfo
+ {
+ Index = reader.GetInt32(1),
+ Item = null!,
+ ItemId = reader.GetGuid(0),
+ };
+
+ if (reader.TryGetString(2, out var codec))
+ {
+ item.Codec = codec;
+ }
+
+ if (reader.TryGetString(3, out var codecTag))
+ {
+ item.CodecTag = codecTag;
+ }
+
+ if (reader.TryGetString(4, out var comment))
+ {
+ item.Comment = comment;
+ }
+
+ if (reader.TryGetString(5, out var fileName))
+ {
+ item.Filename = fileName;
+ }
+
+ if (reader.TryGetString(6, out var mimeType))
+ {
+ item.MimeType = mimeType;
+ }
+
+ return item;
+ }
+
private (BaseItemEntity BaseItem, string[] LegacyUserDataKey) GetItem(SqliteDataReader reader)
{
var entity = new BaseItemEntity()
@@ -1214,4 +1332,58 @@ internal class MigrateLibraryDb : IDatabaseMigrationRoutine
return image;
}
+
+ private class TrackedMigrationStep : IDisposable
+ {
+ private readonly string _operationName;
+ private readonly ILogger _logger;
+ private readonly Stopwatch _operationTimer;
+ private bool _disposed;
+
+ public TrackedMigrationStep(string operationName, ILogger logger)
+ {
+ _operationName = operationName;
+ _logger = logger;
+ _operationTimer = Stopwatch.StartNew();
+ logger.LogInformation("Start {OperationName}", operationName);
+ }
+
+ public bool Disposed
+ {
+ get => _disposed;
+ set => _disposed = value;
+ }
+
+ public virtual void Dispose()
+ {
+ if (Disposed)
+ {
+ return;
+ }
+
+ Disposed = true;
+ _logger.LogInformation("{OperationName} took '{Time}'", _operationName, _operationTimer.Elapsed);
+ }
+ }
+
+ private sealed class DatabaseMigrationStep : TrackedMigrationStep
+ {
+ public DatabaseMigrationStep(JellyfinDbContext jellyfinDbContext, string operationName, ILogger logger) : base(operationName, logger)
+ {
+ JellyfinDbContext = jellyfinDbContext;
+ }
+
+ public JellyfinDbContext JellyfinDbContext { get; }
+
+ public override void Dispose()
+ {
+ if (Disposed)
+ {
+ return;
+ }
+
+ JellyfinDbContext.Dispose();
+ base.Dispose();
+ }
+ }
}
diff --git a/Jellyfin.Server/Migrations/Routines/MigrateLibraryDbCompatibilityCheck.cs b/Jellyfin.Server/Migrations/Routines/MigrateLibraryDbCompatibilityCheck.cs
new file mode 100644
index 000000000..2d5fc2a0d
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Routines/MigrateLibraryDbCompatibilityCheck.cs
@@ -0,0 +1,73 @@
+#pragma warning disable RS0030 // Do not use banned APIs
+
+using System;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Server.ServerSetupApp;
+using MediaBrowser.Controller;
+using Microsoft.Data.Sqlite;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Migrations.Routines;
+
+/// <summary>
+/// The migration routine for checking if the current instance of Jellyfin is compatiable to be upgraded.
+/// </summary>
+[JellyfinMigration("2025-04-20T19:30:00", nameof(MigrateLibraryDbCompatibilityCheck))]
+public class MigrateLibraryDbCompatibilityCheck : IAsyncMigrationRoutine
+{
+ private const string DbFilename = "library.db";
+ private readonly IStartupLogger _logger;
+ private readonly IServerApplicationPaths _paths;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MigrateLibraryDbCompatibilityCheck"/> class.
+ /// </summary>
+ /// <param name="startupLogger">The startup logger.</param>
+ /// <param name="paths">The Path service.</param>
+ public MigrateLibraryDbCompatibilityCheck(IStartupLogger startupLogger, IServerApplicationPaths paths)
+ {
+ _logger = startupLogger;
+ _paths = paths;
+ }
+
+ /// <inheritdoc/>
+ public async Task PerformAsync(CancellationToken cancellationToken)
+ {
+ var dataPath = _paths.DataPath;
+ var libraryDbPath = Path.Combine(dataPath, DbFilename);
+ if (!File.Exists(libraryDbPath))
+ {
+ _logger.LogError("Cannot migrate {LibraryDb} as it does not exist..", libraryDbPath);
+ return;
+ }
+
+ using var connection = new SqliteConnection($"Filename={libraryDbPath};Mode=ReadOnly");
+ await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
+ CheckMigratableVersion(connection);
+ await connection.CloseAsync().ConfigureAwait(false);
+ }
+
+ private static void CheckMigratableVersion(SqliteConnection connection)
+ {
+ CheckColumnExistance(connection, "TypedBaseItems", "lufs");
+ CheckColumnExistance(connection, "TypedBaseItems", "normalizationgain");
+ CheckColumnExistance(connection, "mediastreams", "dvversionmajor");
+
+ static void CheckColumnExistance(SqliteConnection connection, string table, string column)
+ {
+ using (var cmd = connection.CreateCommand())
+ {
+#pragma warning disable CA2100 // Review SQL queries for security vulnerabilities
+ cmd.CommandText = $"Select COUNT(1) FROM pragma_table_xinfo('{table}') WHERE lower(name) = '{column}';";
+#pragma warning restore CA2100 // Review SQL queries for security vulnerabilities
+ var result = cmd.ExecuteScalar()!;
+ if (!result.Equals(1L))
+ {
+ throw new InvalidOperationException("Your database does not meet the required standard. Only upgrades from server version 10.9.11 or above are supported. Please upgrade first to server version 10.10.7 before attempting to upgrade afterwards to 10.11");
+ }
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Server/Migrations/Routines/MigrateRatingLevels.cs b/Jellyfin.Server/Migrations/Routines/MigrateRatingLevels.cs
index 9c2184029..ae93557de 100644
--- a/Jellyfin.Server/Migrations/Routines/MigrateRatingLevels.cs
+++ b/Jellyfin.Server/Migrations/Routines/MigrateRatingLevels.cs
@@ -1,94 +1,69 @@
using System;
-using System.Globalization;
-using System.IO;
-using Emby.Server.Implementations.Data;
-using MediaBrowser.Controller;
+using System.Linq;
+using Jellyfin.Database.Implementations;
+using Jellyfin.Server.ServerSetupApp;
using MediaBrowser.Model.Globalization;
-using Microsoft.Data.Sqlite;
+using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
-namespace Jellyfin.Server.Migrations.Routines
-{
- /// <summary>
- /// Migrate rating levels to new rating level system.
- /// </summary>
- internal class MigrateRatingLevels : IMigrationRoutine
- {
- private const string DbFilename = "library.db";
- private readonly ILogger<MigrateRatingLevels> _logger;
- private readonly IServerApplicationPaths _applicationPaths;
- private readonly ILocalizationManager _localizationManager;
-
- public MigrateRatingLevels(
- IServerApplicationPaths applicationPaths,
- ILoggerFactory loggerFactory,
- ILocalizationManager localizationManager)
- {
- _applicationPaths = applicationPaths;
- _localizationManager = localizationManager;
- _logger = loggerFactory.CreateLogger<MigrateRatingLevels>();
- }
-
- /// <inheritdoc/>
- public Guid Id => Guid.Parse("{73DAB92A-178B-48CD-B05B-FE18733ACDC8}");
+namespace Jellyfin.Server.Migrations.Routines;
- /// <inheritdoc/>
- public string Name => "MigrateRatingLevels";
+/// <summary>
+/// Migrate rating levels.
+/// </summary>
+#pragma warning disable CS0618 // Type or member is obsolete
+[JellyfinMigration("2025-04-20T22: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;
- /// <inheritdoc/>
- public bool PerformOnNewInstall => false;
+ public MigrateRatingLevels(
+ IDbContextFactory<JellyfinDbContext> provider,
+ IStartupLogger logger,
+ ILocalizationManager localizationManager)
+ {
+ _provider = provider;
+ _localizationManager = localizationManager;
+ _logger = logger;
+ }
- /// <inheritdoc/>
- public void Perform()
+ /// <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)
{
- var dbPath = Path.Combine(_applicationPaths.DataPath, DbFilename);
-
- // Back up the database before modifying any entries
- for (int i = 1; ; i++)
+ if (string.IsNullOrEmpty(rating))
{
- var bakPath = string.Format(CultureInfo.InvariantCulture, "{0}.bak{1}", dbPath, i);
- if (!File.Exists(bakPath))
- {
- try
- {
- File.Copy(dbPath, bakPath);
- _logger.LogInformation("Library database backed up to {BackupPath}", bakPath);
- break;
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Cannot make a backup of {Library} at path {BackupPath}", DbFilename, bakPath);
- throw;
- }
- }
+ 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));
}
-
- // Migrate parental rating strings to new levels
- _logger.LogInformation("Recalculating parental rating levels based on rating string.");
- using var connection = new SqliteConnection($"Filename={dbPath}");
- connection.Open();
- using (var transaction = connection.BeginTransaction())
+ else
{
- var queryResult = connection.Query("SELECT DISTINCT OfficialRating FROM TypedBaseItems");
- foreach (var entry in queryResult)
- {
- if (!entry.TryGetString(0, out var ratingString) || string.IsNullOrEmpty(ratingString))
- {
- connection.Execute("UPDATE TypedBaseItems SET InheritedParentalRatingValue = NULL WHERE OfficialRating IS NULL OR OfficialRating='';");
- }
- else
- {
- var ratingValue = _localizationManager.GetRatingLevel(ratingString)?.ToString(CultureInfo.InvariantCulture) ?? "NULL";
-
- using var statement = connection.PrepareStatement("UPDATE TypedBaseItems SET InheritedParentalRatingValue = @Value WHERE OfficialRating = @Rating;");
- statement.TryBind("@Value", ratingValue);
- statement.TryBind("@Rating", ratingString);
- statement.ExecuteNonQuery();
- }
- }
-
- transaction.Commit();
+ 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/MigrateUserDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs
index c40560660..e5584fb94 100644
--- a/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs
+++ b/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs
@@ -17,206 +17,200 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using JsonSerializer = System.Text.Json.JsonSerializer;
-namespace Jellyfin.Server.Migrations.Routines
+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
{
+ private const string DbFilename = "users.db";
+
+ private readonly ILogger<MigrateUserDb> _logger;
+ private readonly IServerApplicationPaths _paths;
+ private readonly IDbContextFactory<JellyfinDbContext> _provider;
+ private readonly IXmlSerializer _xmlSerializer;
+
/// <summary>
- /// The migration routine for migrating the user database to EF Core.
+ /// Initializes a new instance of the <see cref="MigrateUserDb"/> class.
/// </summary>
- public class MigrateUserDb : IMigrationRoutine
+ /// <param name="logger">The logger.</param>
+ /// <param name="paths">The server application paths.</param>
+ /// <param name="provider">The database provider.</param>
+ /// <param name="xmlSerializer">The xml serializer.</param>
+ public MigrateUserDb(
+ ILogger<MigrateUserDb> logger,
+ IServerApplicationPaths paths,
+ IDbContextFactory<JellyfinDbContext> provider,
+ IXmlSerializer xmlSerializer)
{
- private const string DbFilename = "users.db";
-
- private readonly ILogger<MigrateUserDb> _logger;
- private readonly IServerApplicationPaths _paths;
- private readonly IDbContextFactory<JellyfinDbContext> _provider;
- private readonly IXmlSerializer _xmlSerializer;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="MigrateUserDb"/> class.
- /// </summary>
- /// <param name="logger">The logger.</param>
- /// <param name="paths">The server application paths.</param>
- /// <param name="provider">The database provider.</param>
- /// <param name="xmlSerializer">The xml serializer.</param>
- public MigrateUserDb(
- ILogger<MigrateUserDb> logger,
- IServerApplicationPaths paths,
- IDbContextFactory<JellyfinDbContext> provider,
- IXmlSerializer xmlSerializer)
- {
- _logger = logger;
- _paths = paths;
- _provider = provider;
- _xmlSerializer = xmlSerializer;
- }
+ _logger = logger;
+ _paths = paths;
+ _provider = provider;
+ _xmlSerializer = xmlSerializer;
+ }
- /// <inheritdoc/>
- public Guid Id => Guid.Parse("5C4B82A2-F053-4009-BD05-B6FCAD82F14C");
+ /// <inheritdoc/>
+ public void Perform()
+ {
+ var dataPath = _paths.DataPath;
+ _logger.LogInformation("Migrating the user database may take a while, do not stop Jellyfin.");
- /// <inheritdoc/>
- public string Name => "MigrateUserDatabase";
+ using (var connection = new SqliteConnection($"Filename={Path.Combine(dataPath, DbFilename)}"))
+ {
+ connection.Open();
+ using var dbContext = _provider.CreateDbContext();
- /// <inheritdoc/>
- public bool PerformOnNewInstall => false;
+ var queryResult = connection.Query("SELECT * FROM LocalUsersv2");
- /// <inheritdoc/>
- public void Perform()
- {
- var dataPath = _paths.DataPath;
- _logger.LogInformation("Migrating the user database may take a while, do not stop Jellyfin.");
+ dbContext.RemoveRange(dbContext.Users);
+ dbContext.SaveChanges();
- using (var connection = new SqliteConnection($"Filename={Path.Combine(dataPath, DbFilename)}"))
+ foreach (var entry in queryResult)
{
- connection.Open();
- using var dbContext = _provider.CreateDbContext();
-
- var queryResult = connection.Query("SELECT * FROM LocalUsersv2");
+ UserMockup? mockup = JsonSerializer.Deserialize<UserMockup>(entry.GetStream(2), JsonDefaults.Options);
+ if (mockup is null)
+ {
+ continue;
+ }
- dbContext.RemoveRange(dbContext.Users);
- dbContext.SaveChanges();
+ var userDataDir = Path.Combine(_paths.UserConfigurationDirectoryPath, mockup.Name);
+
+ var configPath = Path.Combine(userDataDir, "config.xml");
+ var config = File.Exists(configPath)
+ ? (UserConfiguration?)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), configPath) ?? new UserConfiguration()
+ : new UserConfiguration();
+
+ var policyPath = Path.Combine(userDataDir, "policy.xml");
+ var policy = File.Exists(policyPath)
+ ? (UserPolicy?)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), policyPath) ?? new UserPolicy()
+ : new UserPolicy();
+ policy.AuthenticationProviderId = policy.AuthenticationProviderId?.Replace(
+ "Emby.Server.Implementations.Library",
+ "Jellyfin.Server.Implementations.Users",
+ StringComparison.Ordinal)
+ ?? typeof(DefaultAuthenticationProvider).FullName;
+
+ policy.PasswordResetProviderId = typeof(DefaultPasswordResetProvider).FullName;
+ int? maxLoginAttempts = policy.LoginAttemptsBeforeLockout switch
+ {
+ -1 => null,
+ 0 => 3,
+ _ => policy.LoginAttemptsBeforeLockout
+ };
- foreach (var entry in queryResult)
+ var user = new User(mockup.Name, policy.AuthenticationProviderId!, policy.PasswordResetProviderId!)
{
- UserMockup? mockup = JsonSerializer.Deserialize<UserMockup>(entry.GetStream(2), JsonDefaults.Options);
- if (mockup is null)
- {
- continue;
- }
-
- var userDataDir = Path.Combine(_paths.UserConfigurationDirectoryPath, mockup.Name);
-
- var configPath = Path.Combine(userDataDir, "config.xml");
- var config = File.Exists(configPath)
- ? (UserConfiguration?)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), configPath) ?? new UserConfiguration()
- : new UserConfiguration();
-
- var policyPath = Path.Combine(userDataDir, "policy.xml");
- var policy = File.Exists(policyPath)
- ? (UserPolicy?)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), policyPath) ?? new UserPolicy()
- : new UserPolicy();
- policy.AuthenticationProviderId = policy.AuthenticationProviderId?.Replace(
- "Emby.Server.Implementations.Library",
- "Jellyfin.Server.Implementations.Users",
- StringComparison.Ordinal)
- ?? typeof(DefaultAuthenticationProvider).FullName;
-
- policy.PasswordResetProviderId = typeof(DefaultPasswordResetProvider).FullName;
- int? maxLoginAttempts = policy.LoginAttemptsBeforeLockout switch
- {
- -1 => null,
- 0 => 3,
- _ => policy.LoginAttemptsBeforeLockout
- };
+ Id = entry.GetGuid(1),
+ InternalId = entry.GetInt64(0),
+ MaxParentalRatingScore = policy.MaxParentalRating,
+ MaxParentalRatingSubScore = null,
+ EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess,
+ RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit,
+ InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount,
+ LoginAttemptsBeforeLockout = maxLoginAttempts,
+ SubtitleMode = config.SubtitleMode,
+ HidePlayedInLatest = config.HidePlayedInLatest,
+ EnableLocalPassword = config.EnableLocalPassword,
+ PlayDefaultAudioTrack = config.PlayDefaultAudioTrack,
+ DisplayCollectionsView = config.DisplayCollectionsView,
+ DisplayMissingEpisodes = config.DisplayMissingEpisodes,
+ AudioLanguagePreference = config.AudioLanguagePreference,
+ RememberAudioSelections = config.RememberAudioSelections,
+ EnableNextEpisodeAutoPlay = config.EnableNextEpisodeAutoPlay,
+ RememberSubtitleSelections = config.RememberSubtitleSelections,
+ SubtitleLanguagePreference = config.SubtitleLanguagePreference,
+ Password = mockup.Password,
+ LastLoginDate = mockup.LastLoginDate,
+ LastActivityDate = mockup.LastActivityDate
+ };
+
+ if (mockup.ImageInfos.Length > 0)
+ {
+ ItemImageInfo info = mockup.ImageInfos[0];
- var user = new User(mockup.Name, policy.AuthenticationProviderId!, policy.PasswordResetProviderId!)
+ user.ProfileImage = new ImageInfo(info.Path)
{
- Id = entry.GetGuid(1),
- InternalId = entry.GetInt64(0),
- MaxParentalAgeRating = policy.MaxParentalRating,
- EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess,
- RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit,
- InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount,
- LoginAttemptsBeforeLockout = maxLoginAttempts,
- SubtitleMode = config.SubtitleMode,
- HidePlayedInLatest = config.HidePlayedInLatest,
- EnableLocalPassword = config.EnableLocalPassword,
- PlayDefaultAudioTrack = config.PlayDefaultAudioTrack,
- DisplayCollectionsView = config.DisplayCollectionsView,
- DisplayMissingEpisodes = config.DisplayMissingEpisodes,
- AudioLanguagePreference = config.AudioLanguagePreference,
- RememberAudioSelections = config.RememberAudioSelections,
- EnableNextEpisodeAutoPlay = config.EnableNextEpisodeAutoPlay,
- RememberSubtitleSelections = config.RememberSubtitleSelections,
- SubtitleLanguagePreference = config.SubtitleLanguagePreference,
- Password = mockup.Password,
- LastLoginDate = mockup.LastLoginDate,
- LastActivityDate = mockup.LastActivityDate
+ LastModified = info.DateModified
};
+ }
- if (mockup.ImageInfos.Length > 0)
- {
- ItemImageInfo info = mockup.ImageInfos[0];
-
- user.ProfileImage = new ImageInfo(info.Path)
- {
- LastModified = info.DateModified
- };
- }
-
- user.SetPermission(PermissionKind.IsAdministrator, policy.IsAdministrator);
- user.SetPermission(PermissionKind.IsHidden, policy.IsHidden);
- user.SetPermission(PermissionKind.IsDisabled, policy.IsDisabled);
- user.SetPermission(PermissionKind.EnableSharedDeviceControl, policy.EnableSharedDeviceControl);
- user.SetPermission(PermissionKind.EnableRemoteAccess, policy.EnableRemoteAccess);
- user.SetPermission(PermissionKind.EnableLiveTvManagement, policy.EnableLiveTvManagement);
- user.SetPermission(PermissionKind.EnableLiveTvAccess, policy.EnableLiveTvAccess);
- user.SetPermission(PermissionKind.EnableMediaPlayback, policy.EnableMediaPlayback);
- user.SetPermission(PermissionKind.EnableAudioPlaybackTranscoding, policy.EnableAudioPlaybackTranscoding);
- user.SetPermission(PermissionKind.EnableVideoPlaybackTranscoding, policy.EnableVideoPlaybackTranscoding);
- user.SetPermission(PermissionKind.EnableContentDeletion, policy.EnableContentDeletion);
- user.SetPermission(PermissionKind.EnableContentDownloading, policy.EnableContentDownloading);
- user.SetPermission(PermissionKind.EnableSyncTranscoding, policy.EnableSyncTranscoding);
- user.SetPermission(PermissionKind.EnableMediaConversion, policy.EnableMediaConversion);
- user.SetPermission(PermissionKind.EnableAllChannels, policy.EnableAllChannels);
- user.SetPermission(PermissionKind.EnableAllDevices, policy.EnableAllDevices);
- user.SetPermission(PermissionKind.EnableAllFolders, policy.EnableAllFolders);
- user.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, policy.EnableRemoteControlOfOtherUsers);
- user.SetPermission(PermissionKind.EnablePlaybackRemuxing, policy.EnablePlaybackRemuxing);
- user.SetPermission(PermissionKind.ForceRemoteSourceTranscoding, policy.ForceRemoteSourceTranscoding);
- user.SetPermission(PermissionKind.EnablePublicSharing, policy.EnablePublicSharing);
- user.SetPermission(PermissionKind.EnableCollectionManagement, policy.EnableCollectionManagement);
-
- foreach (var policyAccessSchedule in policy.AccessSchedules)
- {
- user.AccessSchedules.Add(policyAccessSchedule);
- }
-
- user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags);
- user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels);
- user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices);
- user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders);
- user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders);
- user.SetPreference(PreferenceKind.OrderedViews, config.OrderedViews);
- user.SetPreference(PreferenceKind.GroupedFolders, config.GroupedFolders);
- user.SetPreference(PreferenceKind.MyMediaExcludes, config.MyMediaExcludes);
- user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes);
-
- dbContext.Users.Add(user);
+ user.SetPermission(PermissionKind.IsAdministrator, policy.IsAdministrator);
+ user.SetPermission(PermissionKind.IsHidden, policy.IsHidden);
+ user.SetPermission(PermissionKind.IsDisabled, policy.IsDisabled);
+ user.SetPermission(PermissionKind.EnableSharedDeviceControl, policy.EnableSharedDeviceControl);
+ user.SetPermission(PermissionKind.EnableRemoteAccess, policy.EnableRemoteAccess);
+ user.SetPermission(PermissionKind.EnableLiveTvManagement, policy.EnableLiveTvManagement);
+ user.SetPermission(PermissionKind.EnableLiveTvAccess, policy.EnableLiveTvAccess);
+ user.SetPermission(PermissionKind.EnableMediaPlayback, policy.EnableMediaPlayback);
+ user.SetPermission(PermissionKind.EnableAudioPlaybackTranscoding, policy.EnableAudioPlaybackTranscoding);
+ user.SetPermission(PermissionKind.EnableVideoPlaybackTranscoding, policy.EnableVideoPlaybackTranscoding);
+ user.SetPermission(PermissionKind.EnableContentDeletion, policy.EnableContentDeletion);
+ user.SetPermission(PermissionKind.EnableContentDownloading, policy.EnableContentDownloading);
+ user.SetPermission(PermissionKind.EnableSyncTranscoding, policy.EnableSyncTranscoding);
+ user.SetPermission(PermissionKind.EnableMediaConversion, policy.EnableMediaConversion);
+ user.SetPermission(PermissionKind.EnableAllChannels, policy.EnableAllChannels);
+ user.SetPermission(PermissionKind.EnableAllDevices, policy.EnableAllDevices);
+ user.SetPermission(PermissionKind.EnableAllFolders, policy.EnableAllFolders);
+ user.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, policy.EnableRemoteControlOfOtherUsers);
+ user.SetPermission(PermissionKind.EnablePlaybackRemuxing, policy.EnablePlaybackRemuxing);
+ user.SetPermission(PermissionKind.ForceRemoteSourceTranscoding, policy.ForceRemoteSourceTranscoding);
+ user.SetPermission(PermissionKind.EnablePublicSharing, policy.EnablePublicSharing);
+ user.SetPermission(PermissionKind.EnableCollectionManagement, policy.EnableCollectionManagement);
+
+ foreach (var policyAccessSchedule in policy.AccessSchedules)
+ {
+ user.AccessSchedules.Add(policyAccessSchedule);
}
- dbContext.SaveChanges();
+ user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags);
+ user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels);
+ user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices);
+ user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders);
+ user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders);
+ user.SetPreference(PreferenceKind.OrderedViews, config.OrderedViews);
+ user.SetPreference(PreferenceKind.GroupedFolders, config.GroupedFolders);
+ user.SetPreference(PreferenceKind.MyMediaExcludes, config.MyMediaExcludes);
+ user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes);
+
+ dbContext.Users.Add(user);
}
- try
- {
- File.Move(Path.Combine(dataPath, DbFilename), Path.Combine(dataPath, DbFilename + ".old"));
+ dbContext.SaveChanges();
+ }
- var journalPath = Path.Combine(dataPath, DbFilename + "-journal");
- if (File.Exists(journalPath))
- {
- File.Move(journalPath, Path.Combine(dataPath, DbFilename + ".old-journal"));
- }
- }
- catch (IOException e)
+ try
+ {
+ File.Move(Path.Combine(dataPath, DbFilename), Path.Combine(dataPath, DbFilename + ".old"));
+
+ var journalPath = Path.Combine(dataPath, DbFilename + "-journal");
+ if (File.Exists(journalPath))
{
- _logger.LogError(e, "Error renaming legacy user database to 'users.db.old'");
+ File.Move(journalPath, Path.Combine(dataPath, DbFilename + ".old-journal"));
}
}
+ catch (IOException e)
+ {
+ _logger.LogError(e, "Error renaming legacy user database to 'users.db.old'");
+ }
+ }
#nullable disable
- internal class UserMockup
- {
- public string Password { get; set; }
+ internal class UserMockup
+ {
+ public string Password { get; set; }
- public string EasyPassword { get; set; }
+ public string EasyPassword { get; set; }
- public DateTime? LastLoginDate { get; set; }
+ public DateTime? LastLoginDate { get; set; }
- public DateTime? LastActivityDate { get; set; }
+ public DateTime? LastActivityDate { get; set; }
- public string Name { get; set; }
+ public string Name { get; set; }
- public ItemImageInfo[] ImageInfos { get; set; }
- }
+ public ItemImageInfo[] ImageInfos { get; set; }
}
}
diff --git a/Jellyfin.Server/Migrations/Routines/MoveExtractedFiles.cs b/Jellyfin.Server/Migrations/Routines/MoveExtractedFiles.cs
new file mode 100644
index 000000000..6f650f731
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Routines/MoveExtractedFiles.cs
@@ -0,0 +1,295 @@
+#pragma warning disable CA5351 // Do Not Use Broken Cryptographic Algorithms
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Security.Cryptography;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Data.Enums;
+using Jellyfin.Database.Implementations;
+using Jellyfin.Database.Implementations.Entities;
+using Jellyfin.Server.ServerSetupApp;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.IO;
+using MediaBrowser.Model.IO;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Migrations.Routines;
+
+/// <summary>
+/// Migration to move extracted files to the new directories.
+/// </summary>
+[JellyfinMigration("2025-04-20T21:00:00", nameof(MoveExtractedFiles))]
+public class MoveExtractedFiles : IAsyncMigrationRoutine
+{
+ private readonly IApplicationPaths _appPaths;
+ private readonly ILogger _logger;
+ private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
+ private readonly IPathManager _pathManager;
+ private readonly IFileSystem _fileSystem;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MoveExtractedFiles"/> class.
+ /// </summary>
+ /// <param name="appPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="startupLogger">The startup logger for Startup UI intigration.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="pathManager">Instance of the <see cref="IPathManager"/> interface.</param>
+ /// <param name="dbProvider">Instance of the <see cref="IDbContextFactory{JellyfinDbContext}"/> interface.</param>
+ public MoveExtractedFiles(
+ IApplicationPaths appPaths,
+ ILogger<MoveExtractedFiles> logger,
+ IStartupLogger startupLogger,
+ IPathManager pathManager,
+ IFileSystem fileSystem,
+ IDbContextFactory<JellyfinDbContext> dbProvider)
+ {
+ _appPaths = appPaths;
+ _logger = startupLogger.With(logger);
+ _pathManager = pathManager;
+ _fileSystem = fileSystem;
+ _dbProvider = dbProvider;
+ }
+
+ private string SubtitleCachePath => Path.Combine(_appPaths.DataPath, "subtitles");
+
+ private string AttachmentCachePath => Path.Combine(_appPaths.DataPath, "attachments");
+
+ /// <inheritdoc />
+ public async Task PerformAsync(CancellationToken cancellationToken)
+ {
+ const int Limit = 5000;
+ int itemCount = 0;
+
+ var sw = Stopwatch.StartNew();
+
+ using var context = _dbProvider.CreateDbContext();
+ var records = context.BaseItems.Count(b => b.MediaType == MediaType.Video.ToString() && !b.IsVirtualItem && !b.IsFolder);
+ _logger.LogInformation("Checking {Count} items for movable extracted files.", records);
+
+ // Make sure directories exist
+ Directory.CreateDirectory(SubtitleCachePath);
+ Directory.CreateDirectory(AttachmentCachePath);
+
+ await foreach (var result in context.BaseItems
+ .Include(e => e.MediaStreams!.Where(s => s.StreamType == MediaStreamTypeEntity.Subtitle && !s.IsExternal))
+ .Where(b => b.MediaType == MediaType.Video.ToString() && !b.IsVirtualItem && !b.IsFolder)
+ .Select(b => new
+ {
+ b.Id,
+ b.Path,
+ b.MediaStreams
+ })
+ .OrderBy(e => e.Id)
+ .WithPartitionProgress((partition) => _logger.LogInformation("Checked: {Count} - Moved: {Items} - Time: {Time}", partition * Limit, itemCount, sw.Elapsed))
+ .PartitionEagerAsync(Limit, cancellationToken)
+ .WithCancellation(cancellationToken)
+ .ConfigureAwait(false))
+ {
+ if (MoveSubtitleAndAttachmentFiles(result.Id, result.Path, result.MediaStreams, context))
+ {
+ itemCount++;
+ }
+ }
+
+ _logger.LogInformation("Moved files for {Count} items in {Time}", itemCount, sw.Elapsed);
+
+ // Get all subdirectories with 1 character names (those are the legacy directories)
+ var subdirectories = Directory.GetDirectories(SubtitleCachePath, "*", SearchOption.AllDirectories).Where(s => s.Length == SubtitleCachePath.Length + 2).ToList();
+ subdirectories.AddRange(Directory.GetDirectories(AttachmentCachePath, "*", SearchOption.AllDirectories).Where(s => s.Length == AttachmentCachePath.Length + 2));
+
+ // Remove all legacy subdirectories
+ foreach (var subdir in subdirectories)
+ {
+ Directory.Delete(subdir, true);
+ }
+
+ // Remove old cache path
+ var attachmentCachePath = Path.Join(_appPaths.CachePath, "attachments");
+ if (Directory.Exists(attachmentCachePath))
+ {
+ Directory.Delete(attachmentCachePath, true);
+ }
+
+ _logger.LogInformation("Cleaned up left over subtitles and attachments.");
+ }
+
+ private bool MoveSubtitleAndAttachmentFiles(Guid id, string? path, ICollection<MediaStreamInfo>? mediaStreams, JellyfinDbContext context)
+ {
+ var itemIdString = id.ToString("N", CultureInfo.InvariantCulture);
+ var modified = false;
+ if (mediaStreams is not null)
+ {
+ foreach (var mediaStream in mediaStreams)
+ {
+ if (mediaStream.Codec is null)
+ {
+ continue;
+ }
+
+ var mediaStreamIndex = mediaStream.StreamIndex;
+ var extension = GetSubtitleExtension(mediaStream.Codec);
+ var oldSubtitleCachePath = GetOldSubtitleCachePath(path, mediaStreamIndex, extension);
+ if (string.IsNullOrEmpty(oldSubtitleCachePath) || !File.Exists(oldSubtitleCachePath))
+ {
+ continue;
+ }
+
+ var newSubtitleCachePath = _pathManager.GetSubtitlePath(itemIdString, mediaStreamIndex, extension);
+ if (File.Exists(newSubtitleCachePath))
+ {
+ File.Delete(oldSubtitleCachePath);
+ }
+ else
+ {
+ var newDirectory = Path.GetDirectoryName(newSubtitleCachePath);
+ if (newDirectory is not null)
+ {
+ Directory.CreateDirectory(newDirectory);
+ File.Move(oldSubtitleCachePath, newSubtitleCachePath, false);
+ _logger.LogDebug("Moved subtitle {Index} for {Item} from {Source} to {Destination}", mediaStreamIndex, id, oldSubtitleCachePath, newSubtitleCachePath);
+
+ modified = true;
+ }
+ }
+ }
+ }
+
+#pragma warning disable CA1309 // Use ordinal string comparison
+ var attachments = context.AttachmentStreamInfos.Where(a => a.ItemId.Equals(id) && !string.Equals(a.Codec, "mjpeg")).ToList();
+#pragma warning restore CA1309 // Use ordinal string comparison
+ var shouldExtractOneByOne = attachments.Any(a => !string.IsNullOrEmpty(a.Filename)
+ && (a.Filename.Contains('/', StringComparison.OrdinalIgnoreCase) || a.Filename.Contains('\\', StringComparison.OrdinalIgnoreCase)));
+ foreach (var attachment in attachments)
+ {
+ var attachmentIndex = attachment.Index;
+ var oldAttachmentPath = GetOldAttachmentDataPath(path, attachmentIndex);
+ if (string.IsNullOrEmpty(oldAttachmentPath) || !File.Exists(oldAttachmentPath))
+ {
+ oldAttachmentPath = GetOldAttachmentCachePath(itemIdString, attachment, shouldExtractOneByOne);
+ if (string.IsNullOrEmpty(oldAttachmentPath) || !File.Exists(oldAttachmentPath))
+ {
+ continue;
+ }
+ }
+
+ var newAttachmentPath = _pathManager.GetAttachmentPath(itemIdString, attachment.Filename ?? attachmentIndex.ToString(CultureInfo.InvariantCulture));
+ if (File.Exists(newAttachmentPath))
+ {
+ File.Delete(oldAttachmentPath);
+ }
+ else
+ {
+ var newDirectory = Path.GetDirectoryName(newAttachmentPath);
+ if (newDirectory is not null)
+ {
+ Directory.CreateDirectory(newDirectory);
+ File.Move(oldAttachmentPath, newAttachmentPath, false);
+ _logger.LogDebug("Moved attachment {Index} for {Item} from {Source} to {Destination}", attachmentIndex, id, oldAttachmentPath, newAttachmentPath);
+
+ modified = true;
+ }
+ }
+ }
+
+ return modified;
+ }
+
+ private string? GetOldAttachmentDataPath(string? mediaPath, int attachmentStreamIndex)
+ {
+ if (mediaPath is null)
+ {
+ return null;
+ }
+
+ string filename;
+ if (_fileSystem.IsPathFile(mediaPath))
+ {
+ DateTime? date;
+ try
+ {
+ date = File.GetLastWriteTimeUtc(mediaPath);
+ }
+ catch (IOException e)
+ {
+ _logger.LogDebug("Skipping attachment at index {Index} for {Path}: {Exception}", attachmentStreamIndex, mediaPath, e.Message);
+
+ return null;
+ }
+
+ filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Value.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
+ }
+ else
+ {
+ filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
+ }
+
+ return Path.Join(_appPaths.DataPath, "attachments", filename[..1], filename);
+ }
+
+ private string? GetOldAttachmentCachePath(string mediaSourceId, AttachmentStreamInfo attachment, bool shouldExtractOneByOne)
+ {
+ var attachmentFolderPath = Path.Join(_appPaths.CachePath, "attachments", mediaSourceId);
+ if (shouldExtractOneByOne)
+ {
+ return Path.Join(attachmentFolderPath, attachment.Index.ToString(CultureInfo.InvariantCulture));
+ }
+
+ if (string.IsNullOrEmpty(attachment.Filename))
+ {
+ return null;
+ }
+
+ return Path.Join(attachmentFolderPath, attachment.Filename);
+ }
+
+ private string? GetOldSubtitleCachePath(string? path, int streamIndex, string outputSubtitleExtension)
+ {
+ if (path is null)
+ {
+ return null;
+ }
+
+ DateTime? date;
+ try
+ {
+ date = File.GetLastWriteTimeUtc(path);
+ }
+ catch (IOException e)
+ {
+ _logger.LogDebug("Skipping subtitle at index {Index} for {Path}: {Exception}", streamIndex, path, e.Message);
+
+ return null;
+ }
+
+ var ticksParam = string.Empty;
+ ReadOnlySpan<char> filename = new Guid(MD5.HashData(Encoding.Unicode.GetBytes(path + "_" + streamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Value.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam))) + outputSubtitleExtension;
+
+ return Path.Join(SubtitleCachePath, filename[..1], filename);
+ }
+
+ private static string GetSubtitleExtension(string codec)
+ {
+ if (codec.ToLower(CultureInfo.InvariantCulture).Equals("ass", StringComparison.OrdinalIgnoreCase)
+ || codec.ToLower(CultureInfo.InvariantCulture).Equals("ssa", StringComparison.OrdinalIgnoreCase))
+ {
+ return "." + codec;
+ }
+ else if (codec.Contains("pgs", StringComparison.OrdinalIgnoreCase))
+ {
+ return ".sup";
+ }
+ else
+ {
+ return ".srt";
+ }
+ }
+}
diff --git a/Jellyfin.Server/Migrations/Routines/MoveTrickplayFiles.cs b/Jellyfin.Server/Migrations/Routines/MoveTrickplayFiles.cs
index f4ebac377..a674aa928 100644
--- a/Jellyfin.Server/Migrations/Routines/MoveTrickplayFiles.cs
+++ b/Jellyfin.Server/Migrations/Routines/MoveTrickplayFiles.cs
@@ -4,7 +4,7 @@ using System.Globalization;
using System.IO;
using System.Linq;
using Jellyfin.Data.Enums;
-using MediaBrowser.Common;
+using Jellyfin.Server.ServerSetupApp;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Trickplay;
@@ -16,12 +16,15 @@ 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
{
private readonly ITrickplayManager _trickplayManager;
private readonly IFileSystem _fileSystem;
private readonly ILibraryManager _libraryManager;
- private readonly ILogger<MoveTrickplayFiles> _logger;
+ private readonly IStartupLogger _logger;
/// <summary>
/// Initializes a new instance of the <see cref="MoveTrickplayFiles"/> class.
@@ -30,7 +33,11 @@ public class MoveTrickplayFiles : IMigrationRoutine
/// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
/// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
/// <param name="logger">The logger.</param>
- public MoveTrickplayFiles(ITrickplayManager trickplayManager, IFileSystem fileSystem, ILibraryManager libraryManager, ILogger<MoveTrickplayFiles> logger)
+ public MoveTrickplayFiles(
+ ITrickplayManager trickplayManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IStartupLogger logger)
{
_trickplayManager = trickplayManager;
_fileSystem = fileSystem;
@@ -39,18 +46,9 @@ public class MoveTrickplayFiles : IMigrationRoutine
}
/// <inheritdoc />
- public Guid Id => new("9540D44A-D8DC-11EF-9CBB-B77274F77C52");
-
- /// <inheritdoc />
- public string Name => "MoveTrickplayFiles";
-
- /// <inheritdoc />
- public bool PerformOnNewInstall => true;
-
- /// <inheritdoc />
public void Perform()
{
- const int Limit = 100;
+ const int Limit = 5000;
int itemCount = 0, offset = 0, previousCount;
var sw = Stopwatch.StartNew();
@@ -65,9 +63,6 @@ public class MoveTrickplayFiles : IMigrationRoutine
do
{
var trickplayInfos = _trickplayManager.GetTrickplayItemsAsync(Limit, offset).GetAwaiter().GetResult();
- previousCount = trickplayInfos.Count;
- offset += Limit;
-
trickplayQuery.ItemIds = trickplayInfos.Select(i => i.ItemId).Distinct().ToArray();
var items = _libraryManager.GetItemList(trickplayQuery);
foreach (var trickplayInfo in trickplayInfos)
@@ -78,24 +73,32 @@ public class MoveTrickplayFiles : IMigrationRoutine
continue;
}
- if (++itemCount % 1_000 == 0)
- {
- _logger.LogInformation("Moved {Count} items in {Time}", itemCount, sw.Elapsed);
- }
-
+ var moved = false;
var oldPath = GetOldTrickplayDirectory(item, trickplayInfo.Width);
var newPath = _trickplayManager.GetTrickplayDirectory(item, trickplayInfo.TileWidth, trickplayInfo.TileHeight, trickplayInfo.Width, false);
if (_fileSystem.DirectoryExists(oldPath))
{
_fileSystem.MoveDirectory(oldPath, newPath);
+ moved = true;
}
oldPath = GetNewOldTrickplayDirectory(item, trickplayInfo.TileWidth, trickplayInfo.TileHeight, trickplayInfo.Width, false);
if (_fileSystem.DirectoryExists(oldPath))
{
_fileSystem.MoveDirectory(oldPath, newPath);
+ moved = true;
+ }
+
+ if (moved)
+ {
+ itemCount++;
}
}
+
+ offset += Limit;
+ previousCount = trickplayInfos.Count;
+
+ _logger.LogInformation("Checked: {Checked} - Moved: {Count} - Time: {Time}", offset, itemCount, sw.Elapsed);
} while (previousCount == Limit);
_logger.LogInformation("Moved {Count} items in {Time}", itemCount, sw.Elapsed);
diff --git a/Jellyfin.Server/Migrations/Routines/ReaddDefaultPluginRepository.cs b/Jellyfin.Server/Migrations/Routines/ReaddDefaultPluginRepository.cs
index 9cfaec46f..ebf4a2780 100644
--- a/Jellyfin.Server/Migrations/Routines/ReaddDefaultPluginRepository.cs
+++ b/Jellyfin.Server/Migrations/Routines/ReaddDefaultPluginRepository.cs
@@ -2,48 +2,41 @@ using System;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Model.Updates;
-namespace Jellyfin.Server.Migrations.Routines
+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
{
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+
+ private readonly RepositoryInfo _defaultRepositoryInfo = new RepositoryInfo
+ {
+ Name = "Jellyfin Stable",
+ Url = "https://repo.jellyfin.org/releases/plugin/manifest-stable.json"
+ };
+
/// <summary>
- /// Migration to initialize system configuration with the default plugin repository.
+ /// Initializes a new instance of the <see cref="ReaddDefaultPluginRepository"/> class.
/// </summary>
- public class ReaddDefaultPluginRepository : IMigrationRoutine
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ public ReaddDefaultPluginRepository(IServerConfigurationManager serverConfigurationManager)
{
- private readonly IServerConfigurationManager _serverConfigurationManager;
-
- private readonly RepositoryInfo _defaultRepositoryInfo = new RepositoryInfo
- {
- Name = "Jellyfin Stable",
- Url = "https://repo.jellyfin.org/releases/plugin/manifest-stable.json"
- };
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ReaddDefaultPluginRepository"/> class.
- /// </summary>
- /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
- public ReaddDefaultPluginRepository(IServerConfigurationManager serverConfigurationManager)
- {
- _serverConfigurationManager = serverConfigurationManager;
- }
-
- /// <inheritdoc/>
- public Guid Id => Guid.Parse("5F86E7F6-D966-4C77-849D-7A7B40B68C4E");
-
- /// <inheritdoc/>
- public string Name => "ReaddDefaultPluginRepository";
-
- /// <inheritdoc/>
- public bool PerformOnNewInstall => true;
+ _serverConfigurationManager = serverConfigurationManager;
+ }
- /// <inheritdoc/>
- public void Perform()
+ /// <inheritdoc/>
+ public void Perform()
+ {
+ // Only add if repository list is empty
+ if (_serverConfigurationManager.Configuration.PluginRepositories.Length == 0)
{
- // Only add if repository list is empty
- if (_serverConfigurationManager.Configuration.PluginRepositories.Length == 0)
- {
- _serverConfigurationManager.Configuration.PluginRepositories = new[] { _defaultRepositoryInfo };
- _serverConfigurationManager.SaveConfiguration();
- }
+ _serverConfigurationManager.Configuration.PluginRepositories = new[] { _defaultRepositoryInfo };
+ _serverConfigurationManager.SaveConfiguration();
}
}
}
diff --git a/Jellyfin.Server/Migrations/Routines/RefreshInternalDateModified.cs b/Jellyfin.Server/Migrations/Routines/RefreshInternalDateModified.cs
new file mode 100644
index 000000000..b23a7dbc4
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Routines/RefreshInternalDateModified.cs
@@ -0,0 +1,131 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using Jellyfin.Database.Implementations;
+using Jellyfin.Database.Implementations.Entities;
+using Jellyfin.Extensions;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.IO;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Migrations.Routines;
+
+/// <summary>
+/// Migration to re-read creation dates for library items with internal metadata paths.
+/// </summary>
+[JellyfinMigration("2025-04-20T23:00:00", nameof(RefreshInternalDateModified))]
+public class RefreshInternalDateModified : IDatabaseMigrationRoutine
+{
+ private readonly ILogger<RefreshInternalDateModified> _logger;
+ private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
+ private readonly IFileSystem _fileSystem;
+ private readonly IServerApplicationHost _applicationHost;
+ private readonly bool _useFileCreationTimeForDateAdded;
+
+ private IReadOnlyList<string> _internalTypes = [
+ typeof(Genre).FullName!,
+ typeof(MusicGenre).FullName!,
+ typeof(MusicArtist).FullName!,
+ typeof(People).FullName!,
+ typeof(Studio).FullName!
+ ];
+
+ private IReadOnlyList<string> _internalPaths;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RefreshInternalDateModified"/> class.
+ /// </summary>
+ /// <param name="applicationHost">Instance of the <see cref="IServerApplicationHost"/> interface.</param>
+ /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
+ /// <param name="configurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ /// <param name="dbProvider">Instance of the <see cref="IDbContextFactory{JellyfinDbContext}"/> interface.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ public RefreshInternalDateModified(
+ IServerApplicationHost applicationHost,
+ IServerApplicationPaths applicationPaths,
+ IServerConfigurationManager configurationManager,
+ IDbContextFactory<JellyfinDbContext> dbProvider,
+ ILogger<RefreshInternalDateModified> logger,
+ IFileSystem fileSystem)
+ {
+ _dbProvider = dbProvider;
+ _logger = logger;
+ _fileSystem = fileSystem;
+ _applicationHost = applicationHost;
+ _internalPaths = [
+ applicationPaths.ArtistsPath,
+ applicationPaths.GenrePath,
+ applicationPaths.MusicGenrePath,
+ applicationPaths.StudioPath,
+ applicationPaths.PeoplePath
+ ];
+ _useFileCreationTimeForDateAdded = configurationManager.GetMetadataConfiguration().UseFileCreationTimeForDateAdded;
+ }
+
+ /// <inheritdoc />
+ public void Perform()
+ {
+ const int Limit = 5000;
+ int itemCount = 0, offset = 0;
+
+ var sw = Stopwatch.StartNew();
+
+ using var context = _dbProvider.CreateDbContext();
+ var records = context.BaseItems.Count(b => _internalTypes.Contains(b.Type));
+ _logger.LogInformation("Checking if {Count} potentially internal items require refreshed DateModified", records);
+
+ do
+ {
+ var results = context.BaseItems
+ .Where(b => _internalTypes.Contains(b.Type))
+ .OrderBy(e => e.Id)
+ .Skip(offset)
+ .Take(Limit)
+ .ToList();
+
+ foreach (var item in results)
+ {
+ var itemPath = item.Path;
+ if (itemPath is not null)
+ {
+ var realPath = _applicationHost.ExpandVirtualPath(item.Path);
+ if (_internalPaths.Any(path => realPath.StartsWith(path, StringComparison.Ordinal)))
+ {
+ var writeTime = _fileSystem.GetLastWriteTimeUtc(realPath);
+ var itemModificationTime = item.DateModified;
+ if (writeTime != itemModificationTime)
+ {
+ _logger.LogDebug("Reset file modification date: Old: {Old} - New: {New} - Path: {Path}", itemModificationTime, writeTime, realPath);
+ item.DateModified = writeTime;
+ if (_useFileCreationTimeForDateAdded)
+ {
+ item.DateCreated = _fileSystem.GetCreationTimeUtc(realPath);
+ }
+
+ itemCount++;
+ }
+ }
+ }
+ }
+
+ offset += Limit;
+ if (offset > records)
+ {
+ offset = records;
+ }
+
+ _logger.LogInformation("Checked: {Count} - Refreshed: {Items} - Time: {Time}", offset, itemCount, sw.Elapsed);
+ } while (offset < records);
+
+ context.SaveChanges();
+
+ _logger.LogInformation("Refreshed DateModified for {Count} items in {Time}", itemCount, sw.Elapsed);
+ }
+}
diff --git a/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs b/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs
index 52fb93d59..b626c473e 100644
--- a/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs
+++ b/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs
@@ -3,50 +3,43 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using Microsoft.Extensions.Logging;
-namespace Jellyfin.Server.Migrations.Routines
-{
- /// <summary>
- /// Removes the old 'RemoveDownloadImagesInAdvance' from library options.
- /// </summary>
- internal class RemoveDownloadImagesInAdvance : IMigrationRoutine
- {
- private readonly ILogger<RemoveDownloadImagesInAdvance> _logger;
- private readonly ILibraryManager _libraryManager;
-
- public RemoveDownloadImagesInAdvance(ILogger<RemoveDownloadImagesInAdvance> logger, ILibraryManager libraryManager)
- {
- _logger = logger;
- _libraryManager = libraryManager;
- }
-
- /// <inheritdoc/>
- public Guid Id => Guid.Parse("{A81F75E0-8F43-416F-A5E8-516CCAB4D8CC}");
+namespace Jellyfin.Server.Migrations.Routines;
- /// <inheritdoc/>
- public string Name => "RemoveDownloadImagesInAdvance";
+/// <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
+{
+ private readonly ILogger<RemoveDownloadImagesInAdvance> _logger;
+ private readonly ILibraryManager _libraryManager;
- /// <inheritdoc/>
- public bool PerformOnNewInstall => false;
+ public RemoveDownloadImagesInAdvance(ILogger<RemoveDownloadImagesInAdvance> logger, ILibraryManager libraryManager)
+ {
+ _logger = logger;
+ _libraryManager = libraryManager;
+ }
- /// <inheritdoc/>
- public void Perform()
+ /// <inheritdoc/>
+ public void Perform()
+ {
+ var virtualFolders = _libraryManager.GetVirtualFolders(false);
+ _logger.LogInformation("Removing 'RemoveDownloadImagesInAdvance' settings in all the libraries");
+ foreach (var virtualFolder in virtualFolders)
{
- var virtualFolders = _libraryManager.GetVirtualFolders(false);
- _logger.LogInformation("Removing 'RemoveDownloadImagesInAdvance' settings in all the libraries");
- foreach (var virtualFolder in virtualFolders)
+ // Some virtual folders don't have a proper item id.
+ if (!Guid.TryParse(virtualFolder.ItemId, out var folderId))
{
- // Some virtual folders don't have a proper item id.
- if (!Guid.TryParse(virtualFolder.ItemId, out var folderId))
- {
- continue;
- }
-
- var libraryOptions = virtualFolder.LibraryOptions;
- var collectionFolder = _libraryManager.GetItemById<CollectionFolder>(folderId) ?? throw new InvalidOperationException("Failed to find CollectionFolder");
- // The property no longer exists in LibraryOptions, so we just re-save the options to get old data removed.
- collectionFolder.UpdateLibraryOptions(libraryOptions);
- _logger.LogInformation("Removed from '{VirtualFolder}'", virtualFolder.Name);
+ continue;
}
+
+ var libraryOptions = virtualFolder.LibraryOptions;
+ var collectionFolder = _libraryManager.GetItemById<CollectionFolder>(folderId) ?? throw new InvalidOperationException("Failed to find CollectionFolder");
+ // The property no longer exists in LibraryOptions, so we just re-save the options to get old data removed.
+ collectionFolder.UpdateLibraryOptions(libraryOptions);
+ _logger.LogInformation("Removed from '{VirtualFolder}'", virtualFolder.Name);
}
}
}
diff --git a/Jellyfin.Server/Migrations/Routines/RemoveDuplicateExtras.cs b/Jellyfin.Server/Migrations/Routines/RemoveDuplicateExtras.cs
index 7b0d9456d..c9e66d0cf 100644
--- a/Jellyfin.Server/Migrations/Routines/RemoveDuplicateExtras.cs
+++ b/Jellyfin.Server/Migrations/Routines/RemoveDuplicateExtras.cs
@@ -7,77 +7,70 @@ using MediaBrowser.Controller;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Logging;
-namespace Jellyfin.Server.Migrations.Routines
+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
{
- /// <summary>
- /// Remove duplicate entries which were caused by a bug where a file was considered to be an "Extra" to itself.
- /// </summary>
- internal class RemoveDuplicateExtras : IMigrationRoutine
+ private const string DbFilename = "library.db";
+ private readonly ILogger<RemoveDuplicateExtras> _logger;
+ private readonly IServerApplicationPaths _paths;
+
+ public RemoveDuplicateExtras(ILogger<RemoveDuplicateExtras> logger, IServerApplicationPaths paths)
{
- private const string DbFilename = "library.db";
- private readonly ILogger<RemoveDuplicateExtras> _logger;
- private readonly IServerApplicationPaths _paths;
+ _logger = logger;
+ _paths = paths;
+ }
- public RemoveDuplicateExtras(ILogger<RemoveDuplicateExtras> logger, IServerApplicationPaths paths)
+ /// <inheritdoc/>
+ public void Perform()
+ {
+ var dataPath = _paths.DataPath;
+ var dbPath = Path.Combine(dataPath, DbFilename);
+ using var connection = new SqliteConnection($"Filename={dbPath}");
+ connection.Open();
+ using (var transaction = connection.BeginTransaction())
{
- _logger = logger;
- _paths = paths;
- }
+ // Query the database for the ids of duplicate extras
+ var queryResult = connection.Query("SELECT t1.Path FROM TypedBaseItems AS t1, TypedBaseItems AS t2 WHERE t1.Path=t2.Path AND t1.Type!=t2.Type AND t1.Type='MediaBrowser.Controller.Entities.Video'");
+ var bads = string.Join(", ", queryResult.Select(x => x.GetString(0)));
- /// <inheritdoc/>
- public Guid Id => Guid.Parse("{ACBE17B7-8435-4A83-8B64-6FCF162CB9BD}");
-
- /// <inheritdoc/>
- public string Name => "RemoveDuplicateExtras";
-
- /// <inheritdoc/>
- public bool PerformOnNewInstall => false;
-
- /// <inheritdoc/>
- public void Perform()
- {
- var dataPath = _paths.DataPath;
- var dbPath = Path.Combine(dataPath, DbFilename);
- using var connection = new SqliteConnection($"Filename={dbPath}");
- connection.Open();
- using (var transaction = connection.BeginTransaction())
+ // Do nothing if no duplicate extras were detected
+ if (bads.Length == 0)
{
- // Query the database for the ids of duplicate extras
- var queryResult = connection.Query("SELECT t1.Path FROM TypedBaseItems AS t1, TypedBaseItems AS t2 WHERE t1.Path=t2.Path AND t1.Type!=t2.Type AND t1.Type='MediaBrowser.Controller.Entities.Video'");
- var bads = string.Join(", ", queryResult.Select(x => x.GetString(0)));
-
- // Do nothing if no duplicate extras were detected
- if (bads.Length == 0)
- {
- _logger.LogInformation("No duplicate extras detected, skipping migration.");
- return;
- }
+ _logger.LogInformation("No duplicate extras detected, skipping migration.");
+ return;
+ }
- // Back up the database before deleting any entries
- for (int i = 1; ; i++)
+ // Back up the database before deleting any entries
+ for (int i = 1; ; i++)
+ {
+ var bakPath = string.Format(CultureInfo.InvariantCulture, "{0}.bak{1}", dbPath, i);
+ if (!File.Exists(bakPath))
{
- var bakPath = string.Format(CultureInfo.InvariantCulture, "{0}.bak{1}", dbPath, i);
- if (!File.Exists(bakPath))
+ try
{
- try
- {
- File.Copy(dbPath, bakPath);
- _logger.LogInformation("Library database backed up to {BackupPath}", bakPath);
- break;
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Cannot make a backup of {Library} at path {BackupPath}", DbFilename, bakPath);
- throw;
- }
+ File.Copy(dbPath, bakPath);
+ _logger.LogInformation("Library database backed up to {BackupPath}", bakPath);
+ break;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Cannot make a backup of {Library} at path {BackupPath}", DbFilename, bakPath);
+ throw;
}
}
-
- // Delete all duplicate extras
- _logger.LogInformation("Removing found duplicated extras for the following items: {DuplicateExtras}", bads);
- connection.Execute("DELETE FROM TypedBaseItems WHERE rowid IN (SELECT t1.rowid FROM TypedBaseItems AS t1, TypedBaseItems AS t2 WHERE t1.Path=t2.Path AND t1.Type!=t2.Type AND t1.Type='MediaBrowser.Controller.Entities.Video')");
- transaction.Commit();
}
+
+ // Delete all duplicate extras
+ _logger.LogInformation("Removing found duplicated extras for the following items: {DuplicateExtras}", bads);
+ connection.Execute("DELETE FROM TypedBaseItems WHERE rowid IN (SELECT t1.rowid FROM TypedBaseItems AS t1, TypedBaseItems AS t2 WHERE t1.Path=t2.Path AND t1.Type!=t2.Type AND t1.Type='MediaBrowser.Controller.Entities.Video')");
+ transaction.Commit();
}
}
}
diff --git a/Jellyfin.Server/Migrations/Routines/RemoveDuplicatePlaylistChildren.cs b/Jellyfin.Server/Migrations/Routines/RemoveDuplicatePlaylistChildren.cs
index f84bccc25..23f212424 100644
--- a/Jellyfin.Server/Migrations/Routines/RemoveDuplicatePlaylistChildren.cs
+++ b/Jellyfin.Server/Migrations/Routines/RemoveDuplicatePlaylistChildren.cs
@@ -1,44 +1,33 @@
using System;
using System.Linq;
using System.Threading;
-
using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
-using Microsoft.Extensions.Logging;
namespace Jellyfin.Server.Migrations.Routines;
/// <summary>
/// Remove duplicate playlist entries.
/// </summary>
+#pragma warning disable CS0618 // Type or member is obsolete
+[JellyfinMigration("2025-04-20T19:00:00", nameof(RemoveDuplicatePlaylistChildren), "96C156A2-7A13-4B3B-A8B8-FB80C94D20C0")]
internal class RemoveDuplicatePlaylistChildren : IMigrationRoutine
+#pragma warning restore CS0618 // Type or member is obsolete
{
- private readonly ILogger<RemoveDuplicatePlaylistChildren> _logger;
private readonly ILibraryManager _libraryManager;
private readonly IPlaylistManager _playlistManager;
public RemoveDuplicatePlaylistChildren(
- ILogger<RemoveDuplicatePlaylistChildren> logger,
ILibraryManager libraryManager,
IPlaylistManager playlistManager)
{
- _logger = logger;
_libraryManager = libraryManager;
_playlistManager = playlistManager;
}
/// <inheritdoc/>
- public Guid Id => Guid.Parse("{96C156A2-7A13-4B3B-A8B8-FB80C94D20C0}");
-
- /// <inheritdoc/>
- public string Name => "RemoveDuplicatePlaylistChildren";
-
- /// <inheritdoc/>
- public bool PerformOnNewInstall => false;
-
- /// <inheritdoc/>
public void Perform()
{
var playlists = _libraryManager.GetItemList(new InternalItemsQuery
diff --git a/Jellyfin.Server/Migrations/Routines/UpdateDefaultPluginRepository.cs b/Jellyfin.Server/Migrations/Routines/UpdateDefaultPluginRepository.cs
index 7e8c8ac87..f58cf2741 100644
--- a/Jellyfin.Server/Migrations/Routines/UpdateDefaultPluginRepository.cs
+++ b/Jellyfin.Server/Migrations/Routines/UpdateDefaultPluginRepository.cs
@@ -6,7 +6,10 @@ 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
{
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";
@@ -23,15 +26,6 @@ public class UpdateDefaultPluginRepository : IMigrationRoutine
}
/// <inheritdoc />
- public Guid Id => new("852816E0-2712-49A9-9240-C6FC5FCAD1A8");
-
- /// <inheritdoc />
- public string Name => "UpdateDefaultPluginRepository10.9";
-
- /// <inheritdoc />
- public bool PerformOnNewInstall => true;
-
- /// <inheritdoc />
public void Perform()
{
var updated = false;
diff --git a/Jellyfin.Server/Migrations/Stages/CodeMigration.cs b/Jellyfin.Server/Migrations/Stages/CodeMigration.cs
new file mode 100644
index 000000000..47ed26965
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Stages/CodeMigration.cs
@@ -0,0 +1,81 @@
+using System;
+using System.Globalization;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Server.ServerSetupApp;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.DependencyInjection.Extensions;
+
+namespace Jellyfin.Server.Migrations.Stages;
+
+internal class CodeMigration(Type migrationType, JellyfinMigrationAttribute metadata, JellyfinMigrationBackupAttribute? migrationBackupAttribute)
+{
+ public Type MigrationType { get; } = migrationType;
+
+ public JellyfinMigrationAttribute Metadata { get; } = metadata;
+
+ public JellyfinMigrationBackupAttribute? BackupRequirements { get; set; } = migrationBackupAttribute;
+
+ public string BuildCodeMigrationId()
+ {
+ return Metadata.Order.ToString("yyyyMMddHHmmsss", CultureInfo.InvariantCulture) + "_" + Metadata.Name!;
+ }
+
+ private ServiceCollection MigrationServices(IServiceProvider serviceProvider, IStartupLogger logger)
+ {
+ var childServiceCollection = new ServiceCollection();
+ childServiceCollection.AddSingleton(serviceProvider);
+ childServiceCollection.AddSingleton(logger);
+
+ foreach (ServiceDescriptor service in serviceProvider.GetRequiredService<IServiceCollection>())
+ {
+ if (service.Lifetime == ServiceLifetime.Singleton && !service.ServiceType.IsGenericTypeDefinition)
+ {
+ object? serviceInstance = serviceProvider.GetService(service.ServiceType);
+ if (serviceInstance != null)
+ {
+ childServiceCollection.AddSingleton(service.ServiceType, serviceInstance);
+ continue;
+ }
+ }
+
+ childServiceCollection.Add(service);
+ }
+
+ return childServiceCollection;
+ }
+
+ public async Task Perform(IServiceProvider? serviceProvider, IStartupLogger logger, CancellationToken cancellationToken)
+ {
+#pragma warning disable CS0618 // Type or member is obsolete
+ if (typeof(IMigrationRoutine).IsAssignableFrom(MigrationType))
+ {
+ if (serviceProvider is null)
+ {
+ ((IMigrationRoutine)Activator.CreateInstance(MigrationType)!).Perform();
+ }
+ else
+ {
+ using var migrationServices = MigrationServices(serviceProvider, logger).BuildServiceProvider();
+ ((IMigrationRoutine)ActivatorUtilities.CreateInstance(migrationServices, MigrationType)).Perform();
+#pragma warning restore CS0618 // Type or member is obsolete
+ }
+ }
+ else if (typeof(IAsyncMigrationRoutine).IsAssignableFrom(MigrationType))
+ {
+ if (serviceProvider is null)
+ {
+ await ((IAsyncMigrationRoutine)Activator.CreateInstance(MigrationType)!).PerformAsync(cancellationToken).ConfigureAwait(false);
+ }
+ else
+ {
+ using var migrationServices = MigrationServices(serviceProvider, logger).BuildServiceProvider();
+ await ((IAsyncMigrationRoutine)ActivatorUtilities.CreateInstance(migrationServices, MigrationType)).PerformAsync(cancellationToken).ConfigureAwait(false);
+ }
+ }
+ else
+ {
+ throw new InvalidOperationException($"The type {MigrationType} does not implement either IMigrationRoutine or IAsyncMigrationRoutine and is not a valid migration type");
+ }
+ }
+}
diff --git a/Jellyfin.Server/Migrations/Stages/JellyfinMigrationStageTypes.cs b/Jellyfin.Server/Migrations/Stages/JellyfinMigrationStageTypes.cs
new file mode 100644
index 000000000..3d5ec233b
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Stages/JellyfinMigrationStageTypes.cs
@@ -0,0 +1,26 @@
+namespace Jellyfin.Server.Migrations.Stages;
+
+/// <summary>
+/// Defines the stages the <see cref="JellyfinMigrationService"/> supports.
+/// </summary>
+#pragma warning disable CA1008 // Enums should have zero value
+public enum JellyfinMigrationStageTypes
+#pragma warning restore CA1008 // Enums should have zero value
+{
+ /// <summary>
+ /// Runs before services are initialised.
+ /// Reserved for migrations that are modifying the application server itself. Should be avoided if possible.
+ /// </summary>
+ PreInitialisation = 1,
+
+ /// <summary>
+ /// Runs after the host has been configured and includes the database migrations.
+ /// Allows the mix order of migrations that contain application code and database changes.
+ /// </summary>
+ CoreInitialisation = 2,
+
+ /// <summary>
+ /// Runs after services has been registered and initialised. Last step before running the server.
+ /// </summary>
+ AppInitialisation = 3
+}
diff --git a/Jellyfin.Server/Migrations/Stages/MigrationStage.cs b/Jellyfin.Server/Migrations/Stages/MigrationStage.cs
new file mode 100644
index 000000000..efcadbf00
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Stages/MigrationStage.cs
@@ -0,0 +1,16 @@
+using System.Collections.ObjectModel;
+
+namespace Jellyfin.Server.Migrations.Stages;
+
+/// <summary>
+/// Defines a Stage that can be Invoked and Handled at different times from the code.
+/// </summary>
+internal class MigrationStage : Collection<CodeMigration>
+{
+ public MigrationStage(JellyfinMigrationStageTypes stage)
+ {
+ Stage = stage;
+ }
+
+ public JellyfinMigrationStageTypes Stage { get; }
+}
diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs
index e661d0d4a..0b77d63ac 100644
--- a/Jellyfin.Server/Program.cs
+++ b/Jellyfin.Server/Program.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
+using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
@@ -8,15 +9,22 @@ using System.Threading;
using System.Threading.Tasks;
using CommandLine;
using Emby.Server.Implementations;
+using Emby.Server.Implementations.Configuration;
+using Emby.Server.Implementations.Serialization;
using Jellyfin.Database.Implementations;
using Jellyfin.Server.Extensions;
using Jellyfin.Server.Helpers;
+using Jellyfin.Server.Implementations.DatabaseConfiguration;
+using Jellyfin.Server.Implementations.Extensions;
+using Jellyfin.Server.Implementations.StorageHelpers;
+using Jellyfin.Server.Implementations.SystemBackupService;
+using Jellyfin.Server.Migrations;
+using Jellyfin.Server.Migrations.Stages;
using Jellyfin.Server.ServerSetupApp;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using Microsoft.AspNetCore.Hosting;
-using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@@ -46,12 +54,14 @@ namespace Jellyfin.Server
public const string LoggingConfigFileSystem = "logging.json";
private static readonly SerilogLoggerFactory _loggerFactory = new SerilogLoggerFactory();
- private static SetupServer _setupServer = new();
+ private static SetupServer? _setupServer;
private static CoreAppHost? _appHost;
private static IHost? _jellyfinHost = null;
private static long _startTimestamp;
private static ILogger _logger = NullLogger.Instance;
private static bool _restartOnShutdown;
+ private static IStartupLogger? _migrationLogger;
+ private static string? _restoreFromBackup;
/// <summary>
/// The entry point of the application.
@@ -73,9 +83,10 @@ namespace Jellyfin.Server
private static async Task StartApp(StartupOptions options)
{
+ _restoreFromBackup = options.RestoreArchive;
_startTimestamp = Stopwatch.GetTimestamp();
ServerApplicationPaths appPaths = StartupHelpers.CreateApplicationPaths(options);
- await _setupServer.RunAsync(static () => _jellyfinHost?.Services?.GetService<INetworkManager>(), appPaths, static () => _appHost).ConfigureAwait(false);
+ appPaths.MakeSanityCheckOrThrow();
// $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
@@ -88,8 +99,9 @@ namespace Jellyfin.Server
// Create an instance of the application configuration to use for application startup
IConfiguration startupConfig = CreateAppConfiguration(options, appPaths);
-
StartupHelpers.InitializeLoggingFramework(startupConfig, appPaths);
+ _setupServer = new SetupServer(static () => _jellyfinHost?.Services?.GetService<INetworkManager>(), appPaths, static () => _appHost, _loggerFactory, startupConfig);
+ await _setupServer.RunAsync().ConfigureAwait(false);
_logger = _loggerFactory.CreateLogger("Main");
// Use the logging framework for uncaught exceptions instead of std error
@@ -120,8 +132,11 @@ namespace Jellyfin.Server
}
}
+ StorageHelper.TestCommonPathsForStorageCapacity(appPaths, StartupLogger.Logger.With(_loggerFactory.CreateLogger<Startup>()).BeginGroup($"Storage Check"));
+
StartupHelpers.PerformStaticInitialization();
- await Migrations.MigrationRunner.RunPreStartup(appPaths, _loggerFactory).ConfigureAwait(false);
+
+ await ApplyStartupMigrationAsync(appPaths, startupConfig).ConfigureAwait(false);
do
{
@@ -130,10 +145,12 @@ namespace Jellyfin.Server
if (_restartOnShutdown)
{
_startTimestamp = Stopwatch.GetTimestamp();
- _setupServer = new SetupServer();
- await _setupServer.RunAsync(static () => _jellyfinHost?.Services?.GetService<INetworkManager>(), appPaths, static () => _appHost).ConfigureAwait(false);
+ await _setupServer.StopAsync().ConfigureAwait(false);
+ await _setupServer.RunAsync().ConfigureAwait(false);
}
} while (_restartOnShutdown);
+
+ _setupServer.Dispose();
}
private static async Task StartServer(IServerApplicationPaths appPaths, StartupOptions options, IConfiguration startupConfig)
@@ -144,6 +161,7 @@ namespace Jellyfin.Server
options,
startupConfig);
_appHost = appHost;
+ var configurationCompleted = false;
try
{
_jellyfinHost = Host.CreateDefaultBuilder()
@@ -160,19 +178,33 @@ namespace Jellyfin.Server
})
.ConfigureAppConfiguration(config => config.ConfigureAppConfiguration(options, appPaths, startupConfig))
.UseSerilog()
+ .ConfigureServices(e => e.AddTransient<IStartupLogger, StartupLogger>().AddSingleton<IServiceCollection>(e))
.Build();
// Re-use the host service provider in the app host since ASP.NET doesn't allow a custom service collection.
appHost.ServiceProvider = _jellyfinHost.Services;
+ PrepareDatabaseProvider(appHost.ServiceProvider);
+
+ if (!string.IsNullOrWhiteSpace(_restoreFromBackup))
+ {
+ await appHost.ServiceProvider.GetService<IBackupService>()!.RestoreBackupAsync(_restoreFromBackup).ConfigureAwait(false);
+ _restoreFromBackup = null;
+ _restartOnShutdown = true;
+ return;
+ }
+
+ var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(appHost.ServiceProvider);
+ await jellyfinMigrationService.PrepareSystemForMigration(_logger).ConfigureAwait(false);
+ await jellyfinMigrationService.MigrateStepAsync(JellyfinMigrationStageTypes.CoreInitialisation, appHost.ServiceProvider).ConfigureAwait(false);
await appHost.InitializeServices(startupConfig).ConfigureAwait(false);
- await Migrations.MigrationRunner.Run(appHost, _loggerFactory).ConfigureAwait(false);
+ await jellyfinMigrationService.MigrateStepAsync(JellyfinMigrationStageTypes.AppInitialisation, appHost.ServiceProvider).ConfigureAwait(false);
+ await jellyfinMigrationService.CleanupSystemAfterMigration(_logger).ConfigureAwait(false);
try
{
- await _setupServer.StopAsync().ConfigureAwait(false);
- _setupServer.Dispose();
- _setupServer = null!;
+ configurationCompleted = true;
+ await _setupServer!.StopAsync().ConfigureAwait(false);
await _jellyfinHost.StartAsync().ConfigureAwait(false);
if (!OperatingSystem.IsWindows() && startupConfig.UseUnixSocket())
@@ -194,11 +226,18 @@ namespace Jellyfin.Server
await _jellyfinHost.WaitForShutdownAsync().ConfigureAwait(false);
_restartOnShutdown = appHost.ShouldRestart;
+ _restoreFromBackup = appHost.RestoreBackupPath;
}
catch (Exception ex)
{
_restartOnShutdown = false;
_logger.LogCritical(ex, "Error while starting server");
+ if (_setupServer!.IsAlive && !configurationCompleted)
+ {
+ _setupServer!.SoftStop();
+ await Task.Delay(TimeSpan.FromMinutes(10)).ConfigureAwait(false);
+ await _setupServer!.StopAsync().ConfigureAwait(false);
+ }
}
finally
{
@@ -219,6 +258,52 @@ namespace Jellyfin.Server
}
/// <summary>
+ /// [Internal]Runs the startup Migrations.
+ /// </summary>
+ /// <remarks>
+ /// Not intended to be used other then by jellyfin and its tests.
+ /// </remarks>
+ /// <param name="appPaths">Application Paths.</param>
+ /// <param name="startupConfig">Startup Config.</param>
+ /// <returns>A task.</returns>
+ public static async Task ApplyStartupMigrationAsync(ServerApplicationPaths appPaths, IConfiguration startupConfig)
+ {
+ _migrationLogger = StartupLogger.Logger.BeginGroup($"Migration Service");
+ var startupConfigurationManager = new ServerConfigurationManager(appPaths, _loggerFactory, new MyXmlSerializer());
+ startupConfigurationManager.AddParts([new DatabaseConfigurationFactory()]);
+ var migrationStartupServiceProvider = new ServiceCollection()
+ .AddLogging(d => d.AddSerilog())
+ .AddJellyfinDbContext(startupConfigurationManager, startupConfig)
+ .AddSingleton<IApplicationPaths>(appPaths)
+ .AddSingleton<ServerApplicationPaths>(appPaths)
+ .AddSingleton<IStartupLogger>(_migrationLogger);
+
+ migrationStartupServiceProvider.AddSingleton(migrationStartupServiceProvider);
+ var startupService = migrationStartupServiceProvider.BuildServiceProvider();
+
+ PrepareDatabaseProvider(startupService);
+
+ var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(startupService);
+ await jellyfinMigrationService.CheckFirstTimeRunOrMigration(appPaths).ConfigureAwait(false);
+ await jellyfinMigrationService.MigrateStepAsync(Migrations.Stages.JellyfinMigrationStageTypes.PreInitialisation, startupService).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// [Internal]Runs the Jellyfin migrator service with the Core stage.
+ /// </summary>
+ /// <remarks>
+ /// Not intended to be used other then by jellyfin and its tests.
+ /// </remarks>
+ /// <param name="serviceProvider">The service provider.</param>
+ /// <param name="jellyfinMigrationStage">The stage to run.</param>
+ /// <returns>A task.</returns>
+ public static async Task ApplyCoreMigrationsAsync(IServiceProvider serviceProvider, Migrations.Stages.JellyfinMigrationStageTypes jellyfinMigrationStage)
+ {
+ var jellyfinMigrationService = ActivatorUtilities.CreateInstance<JellyfinMigrationService>(serviceProvider, _migrationLogger!);
+ await jellyfinMigrationService.MigrateStepAsync(jellyfinMigrationStage, serviceProvider).ConfigureAwait(false);
+ }
+
+ /// <summary>
/// Create the application configuration.
/// </summary>
/// <param name="commandLineOpts">The command line options passed to the program.</param>
@@ -252,5 +337,12 @@ namespace Jellyfin.Server
.AddEnvironmentVariables("JELLYFIN_")
.AddInMemoryCollection(commandLineOpts.ConvertToConfig());
}
+
+ private static void PrepareDatabaseProvider(IServiceProvider services)
+ {
+ var factory = services.GetRequiredService<IDbContextFactory<JellyfinDbContext>>();
+ var provider = services.GetRequiredService<IJellyfinDatabaseProvider>();
+ provider.DbContextFactory = factory;
+ }
}
}
diff --git a/Jellyfin.Server/ServerSetupApp/IStartupLogger.cs b/Jellyfin.Server/ServerSetupApp/IStartupLogger.cs
new file mode 100644
index 000000000..2c2ef05f8
--- /dev/null
+++ b/Jellyfin.Server/ServerSetupApp/IStartupLogger.cs
@@ -0,0 +1,25 @@
+using System;
+using Morestachio.Helper.Logging;
+using ILogger = Microsoft.Extensions.Logging.ILogger;
+
+namespace Jellyfin.Server.ServerSetupApp;
+
+/// <summary>
+/// Defines the Startup Logger. This logger acts an an aggregate logger that will push though all log messages to both the attached logger as well as the startup UI.
+/// </summary>
+public interface IStartupLogger : ILogger
+{
+ /// <summary>
+ /// Adds another logger instance to this logger for combined logging.
+ /// </summary>
+ /// <param name="logger">Other logger to rely messages to.</param>
+ /// <returns>A combined logger.</returns>
+ IStartupLogger With(ILogger logger);
+
+ /// <summary>
+ /// Opens a new Group logger within the parent logger.
+ /// </summary>
+ /// <param name="logEntry">Defines the log message that introduces the new group.</param>
+ /// <returns>A new logger that can write to the group.</returns>
+ IStartupLogger BeginGroup(FormattableString logEntry);
+}
diff --git a/Jellyfin.Server/ServerSetupApp/SetupServer.cs b/Jellyfin.Server/ServerSetupApp/SetupServer.cs
index 9e2cf5bc8..d88dbee57 100644
--- a/Jellyfin.Server/ServerSetupApp/SetupServer.cs
+++ b/Jellyfin.Server/ServerSetupApp/SetupServer.cs
@@ -1,19 +1,32 @@
using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
+using Emby.Server.Implementations.Configuration;
+using Emby.Server.Implementations.Serialization;
+using Jellyfin.Networking.Manager;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
+using MediaBrowser.Model.IO;
using MediaBrowser.Model.System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Primitives;
+using Morestachio;
+using Morestachio.Framework.IO.SingleStream;
+using Morestachio.Rendering;
namespace Jellyfin.Server.ServerSetupApp;
@@ -22,22 +35,109 @@ namespace Jellyfin.Server.ServerSetupApp;
/// </summary>
public sealed class SetupServer : IDisposable
{
+ private readonly Func<INetworkManager?> _networkManagerFactory;
+ private readonly IApplicationPaths _applicationPaths;
+ private readonly Func<IServerApplicationHost?> _serverFactory;
+ private readonly ILoggerFactory _loggerFactory;
+ private readonly IConfiguration _startupConfiguration;
+ private readonly ServerConfigurationManager _configurationManager;
+ private IRenderer? _startupUiRenderer;
private IHost? _startupServer;
private bool _disposed;
+ private bool _isUnhealthy;
/// <summary>
- /// Starts the Bind-All Setup aspcore server to provide a reflection on the current core setup.
+ /// Initializes a new instance of the <see cref="SetupServer"/> class.
/// </summary>
/// <param name="networkManagerFactory">The networkmanager.</param>
/// <param name="applicationPaths">The application paths.</param>
- /// <param name="serverApplicationHost">The servers application host.</param>
- /// <returns>A Task.</returns>
- public async Task RunAsync(
+ /// <param name="serverApplicationHostFactory">The servers application host.</param>
+ /// <param name="loggerFactory">The logger factory.</param>
+ /// <param name="startupConfiguration">The startup configuration.</param>
+ public SetupServer(
Func<INetworkManager?> networkManagerFactory,
IApplicationPaths applicationPaths,
- Func<IServerApplicationHost?> serverApplicationHost)
+ Func<IServerApplicationHost?> serverApplicationHostFactory,
+ ILoggerFactory loggerFactory,
+ IConfiguration startupConfiguration)
+ {
+ _networkManagerFactory = networkManagerFactory;
+ _applicationPaths = applicationPaths;
+ _serverFactory = serverApplicationHostFactory;
+ _loggerFactory = loggerFactory;
+ _startupConfiguration = startupConfiguration;
+ var xmlSerializer = new MyXmlSerializer();
+ _configurationManager = new ServerConfigurationManager(_applicationPaths, loggerFactory, xmlSerializer);
+ _configurationManager.RegisterConfiguration<NetworkConfigurationFactory>();
+ }
+
+ internal static ConcurrentQueue<StartupLogEntry>? LogQueue { get; set; } = new();
+
+ /// <summary>
+ /// Gets a value indicating whether Startup server is currently running.
+ /// </summary>
+ public bool IsAlive { get; internal set; }
+
+ /// <summary>
+ /// Starts the Bind-All Setup aspcore server to provide a reflection on the current core setup.
+ /// </summary>
+ /// <returns>A Task.</returns>
+ public async Task RunAsync()
{
+ var fileTemplate = await File.ReadAllTextAsync(Path.Combine(AppContext.BaseDirectory, "ServerSetupApp", "index.mstemplate.html")).ConfigureAwait(false);
+ _startupUiRenderer = (await ParserOptionsBuilder.New()
+ .WithTemplate(fileTemplate)
+ .WithFormatter(
+ (StartupLogEntry logEntry, IEnumerable<StartupLogEntry> children) =>
+ {
+ if (children.Any())
+ {
+ var maxLevel = logEntry.LogLevel;
+ var stack = new Stack<StartupLogEntry>(children);
+
+ while (maxLevel != LogLevel.Error && stack.Count > 0 && (logEntry = stack.Pop()) != null) // error is the highest inherted error level.
+ {
+ maxLevel = maxLevel < logEntry.LogLevel ? logEntry.LogLevel : maxLevel;
+ foreach (var child in logEntry.Children)
+ {
+ stack.Push(child);
+ }
+ }
+
+ return maxLevel;
+ }
+
+ return logEntry.LogLevel;
+ },
+ "FormatLogLevel")
+ .WithFormatter(
+ (LogLevel logLevel) =>
+ {
+ switch (logLevel)
+ {
+ case LogLevel.Trace:
+ case LogLevel.Debug:
+ case LogLevel.None:
+ return "success";
+ case LogLevel.Information:
+ return "info";
+ case LogLevel.Warning:
+ return "warn";
+ case LogLevel.Error:
+ return "danger";
+ case LogLevel.Critical:
+ return "danger-strong";
+ }
+
+ return string.Empty;
+ },
+ "ToString")
+ .BuildAndParseAsync()
+ .ConfigureAwait(false))
+ .CreateCompiledRenderer();
+
ThrowIfDisposed();
+ var retryAfterValue = TimeSpan.FromSeconds(5);
_startupServer = Host.CreateDefaultBuilder()
.UseConsoleLifetime()
.ConfigureServices(serv =>
@@ -48,7 +148,23 @@ public sealed class SetupServer : IDisposable
.ConfigureWebHostDefaults(webHostBuilder =>
{
webHostBuilder
- .UseKestrel()
+ .UseKestrel((builderContext, options) =>
+ {
+ var config = _configurationManager.GetNetworkConfiguration()!;
+ var knownBindInterfaces = NetworkManager.GetInterfacesCore(_loggerFactory.CreateLogger<SetupServer>(), config.EnableIPv4, config.EnableIPv6);
+ knownBindInterfaces = NetworkManager.FilterBindSettings(config, knownBindInterfaces.ToList(), config.EnableIPv4, config.EnableIPv6);
+ var bindInterfaces = NetworkManager.GetAllBindInterfaces(false, _configurationManager, knownBindInterfaces, config.EnableIPv4, config.EnableIPv6);
+ Extensions.WebHostBuilderExtensions.SetupJellyfinWebServer(
+ bindInterfaces,
+ config.InternalHttpPort,
+ null,
+ null,
+ _startupConfiguration,
+ _applicationPaths,
+ _loggerFactory.CreateLogger<SetupServer>(),
+ builderContext,
+ options);
+ })
.Configure(app =>
{
app.UseHealthChecks("/health");
@@ -57,16 +173,16 @@ public sealed class SetupServer : IDisposable
{
loggerRoute.Run(async context =>
{
- var networkManager = networkManagerFactory();
+ var networkManager = _networkManagerFactory();
if (context.Connection.RemoteIpAddress is null || networkManager is null || !networkManager.IsInLocalNetwork(context.Connection.RemoteIpAddress))
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return;
}
- var logFilePath = new DirectoryInfo(applicationPaths.LogDirectoryPath)
+ var logFilePath = new DirectoryInfo(_applicationPaths.LogDirectoryPath)
.EnumerateFiles()
- .OrderBy(f => f.CreationTimeUtc)
+ .OrderByDescending(f => f.CreationTimeUtc)
.FirstOrDefault()
?.FullName;
if (logFilePath is not null)
@@ -80,20 +196,20 @@ public sealed class SetupServer : IDisposable
{
systemRoute.Run(async context =>
{
- var jfApplicationHost = serverApplicationHost();
+ var jfApplicationHost = _serverFactory();
var retryCounter = 0;
while (jfApplicationHost is null && retryCounter < 5)
{
await Task.Delay(500).ConfigureAwait(false);
- jfApplicationHost = serverApplicationHost();
+ jfApplicationHost = _serverFactory();
retryCounter++;
}
if (jfApplicationHost is null)
{
context.Response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
- context.Response.Headers.RetryAfter = new Microsoft.Extensions.Primitives.StringValues("60");
+ context.Response.Headers.RetryAfter = new StringValues(retryAfterValue.TotalSeconds.ToString("000", CultureInfo.InvariantCulture));
return;
}
@@ -111,23 +227,30 @@ public sealed class SetupServer : IDisposable
});
});
- app.Run((context) =>
+ app.Run(async (context) =>
{
context.Response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
- context.Response.Headers.RetryAfter = new Microsoft.Extensions.Primitives.StringValues("60");
- context.Response.WriteAsync("<p>Jellyfin Server still starting. Please wait.</p>");
- var networkManager = networkManagerFactory();
- if (networkManager is not null && context.Connection.RemoteIpAddress is not null && networkManager.IsInLocalNetwork(context.Connection.RemoteIpAddress))
- {
- context.Response.WriteAsync("<p>You can download the current logfiles <a href='/startup/logger'>here</a>.</p>");
- }
+ context.Response.Headers.RetryAfter = new StringValues(retryAfterValue.TotalSeconds.ToString("000", CultureInfo.InvariantCulture));
+ context.Response.Headers.ContentType = new StringValues("text/html");
+ var networkManager = _networkManagerFactory();
- return Task.CompletedTask;
+ var startupLogEntries = LogQueue?.ToArray() ?? [];
+ await _startupUiRenderer.RenderAsync(
+ new Dictionary<string, object>()
+ {
+ { "isInReportingMode", _isUnhealthy },
+ { "retryValue", retryAfterValue },
+ { "logs", startupLogEntries },
+ { "localNetworkRequest", networkManager is not null && context.Connection.RemoteIpAddress is not null && networkManager.IsInLocalNetwork(context.Connection.RemoteIpAddress) }
+ },
+ new ByteCounterStream(context.Response.BodyWriter.AsStream(), IODefaults.FileStreamBufferSize, true, _startupUiRenderer.ParserOptions))
+ .ConfigureAwait(false);
});
});
})
.Build();
await _startupServer.StartAsync().ConfigureAwait(false);
+ IsAlive = true;
}
/// <summary>
@@ -143,6 +266,7 @@ public sealed class SetupServer : IDisposable
}
await _startupServer.StopAsync().ConfigureAwait(false);
+ IsAlive = false;
}
/// <inheritdoc/>
@@ -155,6 +279,9 @@ public sealed class SetupServer : IDisposable
_disposed = true;
_startupServer?.Dispose();
+ IsAlive = false;
+ LogQueue?.Clear();
+ LogQueue = null;
}
private void ThrowIfDisposed()
@@ -162,11 +289,88 @@ public sealed class SetupServer : IDisposable
ObjectDisposedException.ThrowIf(_disposed, this);
}
+ internal void SoftStop()
+ {
+ _isUnhealthy = true;
+ }
+
private class SetupHealthcheck : IHealthCheck
{
+ private readonly SetupServer _startupServer;
+
+ public SetupHealthcheck(SetupServer startupServer)
+ {
+ _startupServer = startupServer;
+ }
+
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
+ if (_startupServer._isUnhealthy)
+ {
+ return Task.FromResult(HealthCheckResult.Unhealthy("Server is could not complete startup. Check logs."));
+ }
+
return Task.FromResult(HealthCheckResult.Degraded("Server is still starting up."));
}
}
+
+ internal sealed class SetupLoggerFactory : ILoggerProvider, IDisposable
+ {
+ private bool _disposed;
+
+ public ILogger CreateLogger(string categoryName)
+ {
+ return new CatchingSetupServerLogger();
+ }
+
+ public void Dispose()
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ _disposed = true;
+ }
+ }
+
+ internal sealed class CatchingSetupServerLogger : ILogger
+ {
+ public IDisposable? BeginScope<TState>(TState state)
+ where TState : notnull
+ {
+ return null;
+ }
+
+ public bool IsEnabled(LogLevel logLevel)
+ {
+ return logLevel is LogLevel.Error or LogLevel.Critical;
+ }
+
+ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
+ {
+ if (!IsEnabled(logLevel))
+ {
+ return;
+ }
+
+ LogQueue?.Enqueue(new()
+ {
+ LogLevel = logLevel,
+ Content = formatter(state, exception),
+ DateOfCreation = DateTimeOffset.Now
+ });
+ }
+ }
+
+ internal class StartupLogEntry
+ {
+ public LogLevel LogLevel { get; set; }
+
+ public string? Content { get; set; }
+
+ public DateTimeOffset DateOfCreation { get; set; }
+
+ public List<StartupLogEntry> Children { get; set; } = [];
+ }
}
diff --git a/Jellyfin.Server/ServerSetupApp/StartupLogger.cs b/Jellyfin.Server/ServerSetupApp/StartupLogger.cs
new file mode 100644
index 000000000..2b86dc0c1
--- /dev/null
+++ b/Jellyfin.Server/ServerSetupApp/StartupLogger.cs
@@ -0,0 +1,102 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using Jellyfin.Server.Migrations.Routines;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.ServerSetupApp;
+
+/// <inheritdoc/>
+public class StartupLogger : IStartupLogger
+{
+ private readonly SetupServer.StartupLogEntry? _groupEntry;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StartupLogger"/> class.
+ /// </summary>
+ public StartupLogger()
+ {
+ Loggers = [];
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StartupLogger"/> class.
+ /// </summary>
+ private StartupLogger(SetupServer.StartupLogEntry? groupEntry) : this()
+ {
+ _groupEntry = groupEntry;
+ }
+
+ internal static IStartupLogger Logger { get; } = new StartupLogger();
+
+ private List<ILogger> Loggers { get; set; }
+
+ /// <inheritdoc/>
+ public IStartupLogger BeginGroup(FormattableString logEntry)
+ {
+ var startupEntry = new SetupServer.StartupLogEntry()
+ {
+ Content = logEntry.ToString(CultureInfo.InvariantCulture),
+ DateOfCreation = DateTimeOffset.Now
+ };
+
+ if (_groupEntry is null)
+ {
+ SetupServer.LogQueue?.Enqueue(startupEntry);
+ }
+ else
+ {
+ _groupEntry.Children.Add(startupEntry);
+ }
+
+ return new StartupLogger(startupEntry);
+ }
+
+ /// <inheritdoc/>
+ public IDisposable? BeginScope<TState>(TState state)
+ where TState : notnull
+ {
+ return null;
+ }
+
+ /// <inheritdoc/>
+ public bool IsEnabled(LogLevel logLevel)
+ {
+ return true;
+ }
+
+ /// <inheritdoc/>
+ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
+ {
+ foreach (var item in Loggers.Where(e => e.IsEnabled(logLevel)))
+ {
+ item.Log(logLevel, eventId, state, exception, formatter);
+ }
+
+ var startupEntry = new SetupServer.StartupLogEntry()
+ {
+ LogLevel = logLevel,
+ Content = formatter(state, exception),
+ DateOfCreation = DateTimeOffset.Now
+ };
+
+ if (_groupEntry is null)
+ {
+ SetupServer.LogQueue?.Enqueue(startupEntry);
+ }
+ else
+ {
+ _groupEntry.Children.Add(startupEntry);
+ }
+ }
+
+ /// <inheritdoc/>
+ public IStartupLogger With(ILogger logger)
+ {
+ return new StartupLogger(_groupEntry)
+ {
+ Loggers = [.. Loggers, logger]
+ };
+ }
+}
diff --git a/Jellyfin.Server/ServerSetupApp/index.mstemplate.html b/Jellyfin.Server/ServerSetupApp/index.mstemplate.html
new file mode 100644
index 000000000..747835b2a
--- /dev/null
+++ b/Jellyfin.Server/ServerSetupApp/index.mstemplate.html
@@ -0,0 +1,225 @@
+<!DOCTYPE html>
+<html>
+
+<head>
+ <meta charset="UTF-8" />
+ <title>
+ {{#IF isInReportingMode}}
+ ❌
+ {{/IF}}
+ Jellyfin Startup
+ </title>
+ <style>
+ * {
+ font-family: sans-serif;
+ }
+
+ .flex-row {
+ display: flex;
+ flex-direction: row;
+ flex-wrap: nowrap;
+ justify-content: center;
+ align-items: center;
+ align-content: normal;
+ }
+
+ .flex-col {
+ display: flex;
+ flex-direction: column;
+ flex-wrap: nowrap;
+ justify-content: center;
+ align-items: center;
+ align-content: normal;
+ }
+
+ header {
+ height: 5rem;
+ width: 100%;
+ }
+
+ header svg {
+ height: 3rem;
+ width: 9rem;
+ margin-right: 1rem;
+ }
+
+ /* ol.action-list {
+ list-style-type: none;
+ position: relative;
+ } */
+
+ ol.action-list * {
+ font-family: monospace;
+ font-weight: 300;
+ font-size: clamp(18px, 100vw / var(--width), 20px);
+ font-feature-settings: 'onum', 'pnum';
+ line-height: 1.8;
+ -webkit-text-size-adjust: none;
+ }
+
+ /*
+ ol.action-list li {
+ padding-top: .5rem;
+ }
+
+ ol.action-list li::before {
+ position: absolute;
+ left: -0.8em;
+ font-size: 1.1em;
+ } */
+
+ /* Attribution as heavily inspired by: https://iamkate.com/code/tree-views/ */
+ .action-list {
+ --spacing: 1.4rem;
+ --radius: 14px;
+ }
+
+ .action-list li {
+ display: block;
+ position: relative;
+ padding-left: calc(2 * var(--spacing) - var(--radius) - 1px);
+ }
+
+ .action-list ul {
+ margin-left: calc(var(--radius) - var(--spacing));
+ padding-left: 0;
+ }
+
+ .action-list ul li {
+ border-left: 2px solid #ddd;
+ }
+
+ .action-list ul li:last-child {
+ border-color: transparent;
+ }
+
+ .action-list ul li::before {
+ content: '';
+ display: block;
+ position: absolute;
+ top: calc(var(--spacing) / -2);
+ left: -2px;
+ width: calc(var(--spacing) + 2px);
+ height: calc(var(--spacing) + 1px);
+ border: solid #ddd;
+ border-width: 0 0 2px 2px;
+ }
+
+ .action-list summary {
+ display: block;
+ cursor: pointer;
+ }
+
+ .action-list summary::marker,
+ .action-list summary::-webkit-details-marker {
+ display: none;
+ }
+
+ .action-list summary:focus {
+ outline: none;
+ }
+
+ .action-list summary:focus-visible {
+ outline: 1px dotted #000;
+ }
+
+ .action-list li::after,
+ .action-list summary::before {
+ content: '';
+ display: block;
+ position: absolute;
+ top: calc(var(--spacing) / 2 - var(--radius) + 4px);
+ left: calc(var(--spacing) - var(--radius) - -5px);
+ }
+
+ .action-list summary::before {
+ z-index: 1;
+ /* background: #696 url('expand-collapse.svg') 0 0; */
+ }
+
+ .action-list details[open]>summary::before {
+ background-position: calc(-2 * var(--radius)) 0;
+ }
+
+ .action-list li.danger-item::after,
+ .action-list li.danger-strong-item::after {
+ content: '❌';
+ }
+
+ ol.action-list li span.danger-strong-item {
+ text-decoration-style: solid;
+ text-decoration-color: red;
+ text-decoration-line: underline;
+ }
+
+ ol.action-list li.warn-item::after {
+ content: '⚠️';
+ }
+
+ ol.action-list li.success-item::after {
+ content: '✅';
+ }
+
+ ol.action-list li.info-item::after {
+ content: '🔹';
+ }
+
+ /* End Attribution */
+ </style>
+</head>
+
+<body>
+ <div>
+ <header class="flex-row">
+
+ {{^IF isInReportingMode}}
+ <p>Jellyfin Server still starting. Please wait.</p>
+ {{#ELSE}}
+ <p>Jellyfin Server has encountered an error and was not able to start.</p>
+ {{/ELSE}}
+ {{/IF}}
+
+ {{#IF localNetworkRequest}}
+ <p style="margin-left: 1rem;">You can download the current log file <a href='/startup/logger'
+ target="_blank">here</a>.</p>
+ {{/IF}}
+ </header>
+
+ {{#DECLARE LogEntry |--}}
+ {{#LET children = Children}}
+ <li class="{{FormatLogLevel(children).ToString()}}-item">
+ {{--| #IF children.Count > 0}}
+ <details open>
+ <summary>{{DateOfCreation}} - {{Content}}</summary>
+ <ul class="action-list">
+ {{--| #EACH children.Reverse() |-}}
+ {{#IMPORT 'LogEntry'}}
+ {{--| /EACH |-}}
+ </ul>
+ </details>
+ {{--| #ELSE |-}}
+ <span class="{{FormatLogLevel(children).ToString()}}-item">{{DateOfCreation}} - {{Content}}</span>
+ {{--| /ELSE |--}}
+ {{--| /IF |-}}
+ </li>
+ {{--| /DECLARE}}
+
+ <div class="flex-col">
+ <ol class="action-list">
+ {{#FOREACH log IN logs.Reverse()}}
+ {{#IMPORT 'LogEntry' #WITH log}}
+ {{/FOREACH}}
+ </ol>
+ </div>
+ </div>
+</body>
+
+{{^IF isInReportingMode}}
+<script>
+ setTimeout(() => {
+ window.location.reload();
+ }, {{ retryValue.TotalMilliseconds }});
+</script>
+{{/IF}}
+
+</html>
diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs
index 688b16935..aa8f6dd1c 100644
--- a/Jellyfin.Server/Startup.cs
+++ b/Jellyfin.Server/Startup.cs
@@ -1,4 +1,5 @@
using System;
+using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
@@ -29,6 +30,7 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Primitives;
using Prometheus;
namespace Jellyfin.Server
@@ -195,7 +197,14 @@ namespace Jellyfin.Server
{
FileProvider = new PhysicalFileProvider(_serverConfigurationManager.ApplicationPaths.WebPath),
RequestPath = "/web",
- ContentTypeProvider = extensionProvider
+ ContentTypeProvider = extensionProvider,
+ OnPrepareResponse = (context) =>
+ {
+ if (Path.GetFileName(context.File.Name).Equals("index.html", StringComparison.Ordinal))
+ {
+ context.Context.Response.Headers.CacheControl = new StringValues("no-cache");
+ }
+ }
});
mainApp.UseRobotsRedirection();
@@ -208,7 +217,6 @@ namespace Jellyfin.Server
mainApp.UseRouting();
mainApp.UseAuthorization();
- mainApp.UseLanFiltering();
mainApp.UseIPBasedAccessValidation();
mainApp.UseWebSocketHandler();
mainApp.UseServerStartupMessage();
diff --git a/Jellyfin.Server/StartupOptions.cs b/Jellyfin.Server/StartupOptions.cs
index 91ac827ca..4890ccbb2 100644
--- a/Jellyfin.Server/StartupOptions.cs
+++ b/Jellyfin.Server/StartupOptions.cs
@@ -74,6 +74,12 @@ namespace Jellyfin.Server
public bool NoDetectNetworkChange { get; set; }
/// <summary>
+ /// Gets or sets the path to an jellyfin backup archive to restore the application to.
+ /// </summary>
+ [Option("restore-archive", Required = false, HelpText = "Path to a Jellyfin backup archive to restore from")]
+ public string? RestoreArchive { get; set; }
+
+ /// <summary>
/// Gets the command line options as a dictionary that can be used in the .NET configuration system.
/// </summary>
/// <returns>The configuration dictionary.</returns>
diff --git a/MediaBrowser.Common/Configuration/EncodingConfigurationExtensions.cs b/MediaBrowser.Common/Configuration/EncodingConfigurationExtensions.cs
index 70a4fe409..78e96ab47 100644
--- a/MediaBrowser.Common/Configuration/EncodingConfigurationExtensions.cs
+++ b/MediaBrowser.Common/Configuration/EncodingConfigurationExtensions.cs
@@ -35,8 +35,7 @@ namespace MediaBrowser.Common.Configuration
transcodingTempPath = Path.Combine(configurationManager.CommonApplicationPaths.CachePath, "transcodes");
}
- // Make sure the directory exists
- Directory.CreateDirectory(transcodingTempPath);
+ configurationManager.CommonApplicationPaths.CreateAndCheckMarker(transcodingTempPath, "transcode", true);
return transcodingTempPath;
}
}
diff --git a/MediaBrowser.Common/Configuration/IApplicationPaths.cs b/MediaBrowser.Common/Configuration/IApplicationPaths.cs
index 7a8ab3236..6d1a72b04 100644
--- a/MediaBrowser.Common/Configuration/IApplicationPaths.cs
+++ b/MediaBrowser.Common/Configuration/IApplicationPaths.cs
@@ -90,5 +90,24 @@ namespace MediaBrowser.Common.Configuration
/// </summary>
/// <value>The trickplay path.</value>
string TrickplayPath { get; }
+
+ /// <summary>
+ /// Gets the path used for storing backup archives.
+ /// </summary>
+ /// <value>The backup path.</value>
+ string BackupPath { get; }
+
+ /// <summary>
+ /// Checks and creates all known base paths.
+ /// </summary>
+ void MakeSanityCheckOrThrow();
+
+ /// <summary>
+ /// Checks and creates the given path and adds it with a marker file if non existant.
+ /// </summary>
+ /// <param name="path">The path to check.</param>
+ /// <param name="markerName">The common marker file name.</param>
+ /// <param name="recursive">Check for other settings paths recursivly.</param>
+ void CreateAndCheckMarker(string path, string markerName, bool recursive = false);
}
}
diff --git a/MediaBrowser.Common/Extensions/HttpContextExtensions.cs b/MediaBrowser.Common/Extensions/HttpContextExtensions.cs
index a1056b7c8..739a53c7a 100644
--- a/MediaBrowser.Common/Extensions/HttpContextExtensions.cs
+++ b/MediaBrowser.Common/Extensions/HttpContextExtensions.cs
@@ -12,7 +12,7 @@ namespace MediaBrowser.Common.Extensions
/// Checks the origin of the HTTP context.
/// </summary>
/// <param name="context">The incoming HTTP context.</param>
- /// <returns><c>true</c> if the request is coming from LAN, <c>false</c> otherwise.</returns>
+ /// <returns><c>true</c> if the request is coming from the same machine as is running the server, <c>false</c> otherwise.</returns>
public static bool IsLocal(this HttpContext context)
{
return (context.Connection.LocalIpAddress is null
diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs
index d838144ff..bd785bcbc 100644
--- a/MediaBrowser.Common/Net/INetworkManager.cs
+++ b/MediaBrowser.Common/Net/INetworkManager.cs
@@ -127,7 +127,7 @@ namespace MediaBrowser.Common.Net
/// Checks if <paramref name="remoteIP"/> has access to the server.
/// </summary>
/// <param name="remoteIP">IP address of the client.</param>
- /// <returns><b>True</b> if it has access, otherwise <b>false</b>.</returns>
- bool HasRemoteAccess(IPAddress remoteIP);
+ /// <returns>The result of evaluating the access policy, <c>Allow</c> if it should be allowed.</returns>
+ RemoteAccessPolicyResult ShouldAllowServerAccess(IPAddress remoteIP);
}
}
diff --git a/MediaBrowser.Common/Net/NetworkUtils.cs b/MediaBrowser.Common/Net/NetworkUtils.cs
index a498d6271..24ed47a81 100644
--- a/MediaBrowser.Common/Net/NetworkUtils.cs
+++ b/MediaBrowser.Common/Net/NetworkUtils.cs
@@ -198,14 +198,25 @@ public static partial class NetworkUtils
/// <returns><c>True</c> if parsing was successful.</returns>
public static bool TryParseToSubnet(ReadOnlySpan<char> value, [NotNullWhen(true)] out IPNetwork? result, bool negated = false)
{
+ // If multiple IP addresses are in a comma-separated string, the individual addresses may contain leading and/or trailing whitespace
value = value.Trim();
+
+ bool isAddressNegated = false;
+ if (value.StartsWith('!'))
+ {
+ isAddressNegated = true;
+ value = value[1..]; // Remove leading '!' character
+ }
+
+ if (isAddressNegated != negated)
+ {
+ result = null;
+ return false;
+ }
+
if (value.Contains('/'))
{
- if (negated && value.StartsWith("!") && IPNetwork.TryParse(value[1..], out result))
- {
- return true;
- }
- else if (!negated && IPNetwork.TryParse(value, out result))
+ if (IPNetwork.TryParse(value, out result))
{
return true;
}
diff --git a/MediaBrowser.Common/Net/RemoteAccessPolicyResult.cs b/MediaBrowser.Common/Net/RemoteAccessPolicyResult.cs
new file mode 100644
index 000000000..193d37228
--- /dev/null
+++ b/MediaBrowser.Common/Net/RemoteAccessPolicyResult.cs
@@ -0,0 +1,29 @@
+using System;
+
+namespace MediaBrowser.Common.Net;
+
+/// <summary>
+/// Result of <see cref="INetworkManager.ShouldAllowServerAccess" />.
+/// </summary>
+public enum RemoteAccessPolicyResult
+{
+ /// <summary>
+ /// The connection should be allowed.
+ /// </summary>
+ Allow,
+
+ /// <summary>
+ /// The connection should be rejected since it is not from a local IP and remote access is disabled.
+ /// </summary>
+ RejectDueToRemoteAccessDisabled,
+
+ /// <summary>
+ /// The connection should be rejected since it is from a blocklisted IP.
+ /// </summary>
+ RejectDueToIPBlocklist,
+
+ /// <summary>
+ /// The connection should be rejected since it is from a remote IP that is not in the allowlist.
+ /// </summary>
+ RejectDueToNotAllowlistedRemoteIP,
+}
diff --git a/MediaBrowser.Common/Plugins/BasePluginOfT.cs b/MediaBrowser.Common/Plugins/BasePluginOfT.cs
index 58992ecd7..30c67fa05 100644
--- a/MediaBrowser.Common/Plugins/BasePluginOfT.cs
+++ b/MediaBrowser.Common/Plugins/BasePluginOfT.cs
@@ -145,10 +145,7 @@ namespace MediaBrowser.Common.Plugins
lock (_configurationSaveLock)
{
var folder = Path.GetDirectoryName(ConfigurationFilePath);
- if (!Directory.Exists(folder))
- {
- Directory.CreateDirectory(folder);
- }
+ Directory.CreateDirectory(folder);
XmlSerializer.SerializeToFile(config, ConfigurationFilePath);
}
diff --git a/MediaBrowser.Controller/Chapters/IChapterManager.cs b/MediaBrowser.Controller/Chapters/IChapterManager.cs
new file mode 100644
index 000000000..7532e56c6
--- /dev/null
+++ b/MediaBrowser.Controller/Chapters/IChapterManager.cs
@@ -0,0 +1,55 @@
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+
+namespace MediaBrowser.Controller.Chapters;
+
+/// <summary>
+/// Interface IChapterManager.
+/// </summary>
+public interface IChapterManager
+{
+ /// <summary>
+ /// Saves the chapters.
+ /// </summary>
+ /// <param name="video">The video.</param>
+ /// <param name="chapters">The set of chapters.</param>
+ void SaveChapters(Video video, IReadOnlyList<ChapterInfo> chapters);
+
+ /// <summary>
+ /// Gets a single chapter of a BaseItem on a specific index.
+ /// </summary>
+ /// <param name="baseItemId">The BaseItems id.</param>
+ /// <param name="index">The index of that chapter.</param>
+ /// <returns>A chapter instance.</returns>
+ ChapterInfo? GetChapter(Guid baseItemId, int index);
+
+ /// <summary>
+ /// Gets all chapters associated with the baseItem.
+ /// </summary>
+ /// <param name="baseItemId">The BaseItems id.</param>
+ /// <returns>A readonly list of chapter instances.</returns>
+ IReadOnlyList<ChapterInfo> GetChapters(Guid baseItemId);
+
+ /// <summary>
+ /// Refreshes the chapter images.
+ /// </summary>
+ /// <param name="video">Video to use.</param>
+ /// <param name="directoryService">Directory service to use.</param>
+ /// <param name="chapters">Set of chapters to refresh.</param>
+ /// <param name="extractImages">Option to extract images.</param>
+ /// <param name="saveChapters">Option to save chapters.</param>
+ /// <param name="cancellationToken">CancellationToken to use for operation.</param>
+ /// <returns><c>true</c> if successful, <c>false</c> if not.</returns>
+ Task<bool> RefreshChapterImages(Video video, IDirectoryService directoryService, IReadOnlyList<ChapterInfo> chapters, bool extractImages, bool saveChapters, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Deletes the chapter images.
+ /// </summary>
+ /// <param name="video">Video to use.</param>
+ void DeleteChapterImages(Video video);
+}
diff --git a/MediaBrowser.Controller/Dto/DtoOptions.cs b/MediaBrowser.Controller/Dto/DtoOptions.cs
index cb638cf90..a71cdbd62 100644
--- a/MediaBrowser.Controller/Dto/DtoOptions.cs
+++ b/MediaBrowser.Controller/Dto/DtoOptions.cs
@@ -34,7 +34,7 @@ namespace MediaBrowser.Controller.Dto
EnableUserData = true;
AddCurrentProgram = true;
- Fields = allFields ? AllItemFields : Array.Empty<ItemFields>();
+ Fields = allFields ? AllItemFields : [];
ImageTypes = AllImageTypes;
}
diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs
index 53c832ff3..c2efa4ad3 100644
--- a/MediaBrowser.Controller/Entities/BaseItem.cs
+++ b/MediaBrowser.Controller/Entities/BaseItem.cs
@@ -25,6 +25,7 @@ using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaSegments;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Dto;
@@ -34,7 +35,6 @@ using MediaBrowser.Model.IO;
using MediaBrowser.Model.Library;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.MediaInfo;
-using MediaBrowser.Model.Providers;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities
@@ -52,7 +52,7 @@ namespace MediaBrowser.Controller.Entities
/// The supported image extensions.
/// </summary>
public static readonly string[] SupportedImageExtensions
- = new[] { ".png", ".jpg", ".jpeg", ".webp", ".tbn", ".gif", ".svg" };
+ = [".png", ".jpg", ".jpeg", ".webp", ".tbn", ".gif", ".svg"];
private static readonly List<string> _supportedExtensions = new List<string>(SupportedImageExtensions)
{
@@ -448,7 +448,7 @@ namespace MediaBrowser.Controller.Entities
return Array.Empty<string>();
}
- return new[] { Path };
+ return [Path];
}
}
@@ -484,7 +484,7 @@ namespace MediaBrowser.Controller.Entities
public static IItemRepository ItemRepository { get; set; }
- public static IChapterRepository ChapterRepository { get; set; }
+ public static IChapterManager ChapterManager { get; set; }
public static IFileSystem FileSystem { get; set; }
@@ -581,6 +581,9 @@ namespace MediaBrowser.Controller.Entities
[JsonIgnore]
public int? InheritedParentalRatingValue { get; set; }
+ [JsonIgnore]
+ public int? InheritedParentalRatingSubValue { get; set; }
+
/// <summary>
/// Gets or sets the critic rating.
/// </summary>
@@ -1263,7 +1266,7 @@ namespace MediaBrowser.Controller.Entities
}
/// <summary>
- /// Overrides the base implementation to refresh metadata for local trailers.
+ /// The base implementation to refresh metadata.
/// </summary>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
@@ -1360,9 +1363,7 @@ namespace MediaBrowser.Controller.Entities
protected virtual FileSystemMetadata[] GetFileSystemChildren(IDirectoryService directoryService)
{
- var path = ContainingFolderPath;
-
- return directoryService.GetFileSystemEntries(path);
+ return directoryService.GetFileSystemEntries(ContainingFolderPath);
}
private async Task<bool> RefreshExtras(BaseItem item, MetadataRefreshOptions options, IReadOnlyList<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
@@ -1391,6 +1392,23 @@ namespace MediaBrowser.Controller.Entities
return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
});
+ // Cleanup removed extras
+ var removedExtraIds = item.ExtraIds.Where(e => !newExtraIds.Contains(e)).ToArray();
+ if (removedExtraIds.Length > 0)
+ {
+ var removedExtras = LibraryManager.GetItemList(new InternalItemsQuery()
+ {
+ ItemIds = removedExtraIds
+ });
+ foreach (var removedExtra in removedExtras)
+ {
+ LibraryManager.DeleteItem(removedExtra, new DeleteOptions()
+ {
+ DeleteFileLocation = false
+ });
+ }
+ }
+
await Task.WhenAll(tasks).ConfigureAwait(false);
item.ExtraIds = newExtraIds;
@@ -1405,6 +1423,22 @@ namespace MediaBrowser.Controller.Entities
public virtual bool RequiresRefresh()
{
+ if (string.IsNullOrEmpty(Path) || DateModified == default)
+ {
+ return false;
+ }
+
+ var info = FileSystem.GetFileSystemInfo(Path);
+ if (info.Exists)
+ {
+ if (info.IsDirectory)
+ {
+ return info.LastWriteTimeUtc != DateModified;
+ }
+
+ return info.LastWriteTimeUtc != DateModified;
+ }
+
return false;
}
@@ -1540,7 +1574,8 @@ namespace MediaBrowser.Controller.Entities
return false;
}
- var maxAllowedRating = user.MaxParentalAgeRating;
+ var maxAllowedRating = user.MaxParentalRatingScore;
+ var maxAllowedSubRating = user.MaxParentalRatingSubScore;
var rating = CustomRatingForComparison;
if (string.IsNullOrEmpty(rating))
@@ -1554,10 +1589,10 @@ namespace MediaBrowser.Controller.Entities
return !GetBlockUnratedValue(user);
}
- var value = LocalizationManager.GetRatingLevel(rating);
+ var ratingScore = LocalizationManager.GetRatingScore(rating);
// Could not determine rating level
- if (!value.HasValue)
+ if (ratingScore is null)
{
var isAllowed = !GetBlockUnratedValue(user);
@@ -1569,10 +1604,15 @@ namespace MediaBrowser.Controller.Entities
return isAllowed;
}
- return !maxAllowedRating.HasValue || value.Value <= maxAllowedRating.Value;
+ if (maxAllowedSubRating is not null)
+ {
+ return (ratingScore.SubScore ?? 0) <= maxAllowedSubRating && ratingScore.Score <= maxAllowedRating.Value;
+ }
+
+ return !maxAllowedRating.HasValue || ratingScore.Score <= maxAllowedRating.Value;
}
- public int? GetInheritedParentalRatingValue()
+ public ParentalRatingScore GetParentalRatingScore()
{
var rating = CustomRatingForComparison;
@@ -1586,7 +1626,7 @@ namespace MediaBrowser.Controller.Entities
return null;
}
- return LocalizationManager.GetRatingLevel(rating);
+ return LocalizationManager.GetRatingScore(rating);
}
public List<string> GetInheritedTags()
@@ -1796,7 +1836,7 @@ namespace MediaBrowser.Controller.Entities
public void SetStudios(IEnumerable<string> names)
{
- Studios = names.Trimmed().Distinct().ToArray();
+ Studios = names.Trimmed().Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
}
/// <summary>
@@ -1975,7 +2015,7 @@ namespace MediaBrowser.Controller.Entities
public void RemoveImage(ItemImageInfo image)
{
- RemoveImages(new[] { image });
+ RemoveImages([image]);
}
public void RemoveImages(IEnumerable<ItemImageInfo> deletedImages)
@@ -2010,7 +2050,7 @@ namespace MediaBrowser.Controller.Entities
continue;
}
- (deletedImages ??= new List<ItemImageInfo>()).Add(imageInfo);
+ (deletedImages ??= []).Add(imageInfo);
}
var anyImagesRemoved = deletedImages?.Count > 0;
@@ -2042,7 +2082,7 @@ namespace MediaBrowser.Controller.Entities
{
if (imageType == ImageType.Chapter)
{
- var chapter = ChapterRepository.GetChapter(this.Id, imageIndex);
+ var chapter = ChapterManager.GetChapter(Id, imageIndex);
if (chapter is null)
{
@@ -2092,7 +2132,7 @@ namespace MediaBrowser.Controller.Entities
if (image.Type == ImageType.Chapter)
{
- var chapters = ChapterRepository.GetChapters(this.Id);
+ var chapters = ChapterManager.GetChapters(Id);
for (var i = 0; i < chapters.Count; i++)
{
if (chapters[i].ImagePath == image.Path)
@@ -2213,11 +2253,7 @@ namespace MediaBrowser.Controller.Entities
{
return new[]
{
- new FileSystemMetadata
- {
- FullName = Path,
- IsDirectory = IsFolder
- }
+ FileSystem.GetFileSystemInfo(Path)
}.Concat(GetLocalMetadataFilesToDelete());
}
@@ -2225,7 +2261,7 @@ namespace MediaBrowser.Controller.Entities
{
if (IsFolder || !IsInMixedFolder)
{
- return new List<FileSystemMetadata>();
+ return [];
}
var filename = System.IO.Path.GetFileNameWithoutExtension(Path);
@@ -2481,10 +2517,10 @@ namespace MediaBrowser.Controller.Entities
protected virtual List<string> GetEtagValues(User user)
{
- return new List<string>
- {
+ return
+ [
DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
- };
+ ];
}
public virtual IEnumerable<Guid> GetAncestorIds()
@@ -2504,7 +2540,7 @@ namespace MediaBrowser.Controller.Entities
public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
{
- return new[] { Id };
+ return [Id];
}
public virtual double? GetRefreshProgress()
@@ -2518,11 +2554,29 @@ namespace MediaBrowser.Controller.Entities
var item = this;
- var inheritedParentalRatingValue = item.GetInheritedParentalRatingValue() ?? null;
- if (inheritedParentalRatingValue != item.InheritedParentalRatingValue)
+ var rating = item.GetParentalRatingScore();
+ if (rating is not null)
{
- item.InheritedParentalRatingValue = inheritedParentalRatingValue;
- updateType |= ItemUpdateType.MetadataImport;
+ if (rating.Score != item.InheritedParentalRatingValue)
+ {
+ item.InheritedParentalRatingValue = rating.Score;
+ updateType |= ItemUpdateType.MetadataImport;
+ }
+
+ if (rating.SubScore != item.InheritedParentalRatingSubValue)
+ {
+ item.InheritedParentalRatingSubValue = rating.SubScore;
+ updateType |= ItemUpdateType.MetadataImport;
+ }
+ }
+ else
+ {
+ if (item.InheritedParentalRatingValue is not null)
+ {
+ item.InheritedParentalRatingValue = null;
+ item.InheritedParentalRatingSubValue = null;
+ updateType |= ItemUpdateType.MetadataImport;
+ }
}
return updateType;
@@ -2542,8 +2596,9 @@ namespace MediaBrowser.Controller.Entities
.Select(i => i.OfficialRating)
.Where(i => !string.IsNullOrEmpty(i))
.Distinct(StringComparer.OrdinalIgnoreCase)
- .Select(rating => (rating, LocalizationManager.GetRatingLevel(rating)))
- .OrderBy(i => i.Item2 ?? 1000)
+ .Select(rating => (rating, LocalizationManager.GetRatingScore(rating)))
+ .OrderBy(i => i.Item2 is null ? 1001 : i.Item2.Score)
+ .ThenBy(i => i.Item2 is null ? 1001 : i.Item2.SubScore)
.Select(i => i.rating);
OfficialRating = ratings.FirstOrDefault() ?? currentOfficialRating;
diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs
index 4da22854b..e0c3b0a93 100644
--- a/MediaBrowser.Controller/Entities/Folder.cs
+++ b/MediaBrowser.Controller/Entities/Folder.cs
@@ -1222,11 +1222,6 @@ namespace MediaBrowser.Controller.Entities
return false;
}
- if (request.IsPlayed.HasValue)
- {
- return false;
- }
-
if (!string.IsNullOrWhiteSpace(request.Person))
{
return false;
@@ -1267,17 +1262,15 @@ namespace MediaBrowser.Controller.Entities
return false;
}
- if (request.MinCommunityRating.HasValue)
- {
- return false;
- }
-
- if (request.MinCriticRating.HasValue)
+ if (request.MinIndexNumber.HasValue)
{
return false;
}
- if (request.MinIndexNumber.HasValue)
+ if (request.OrderBy.Any(o =>
+ o.OrderBy == ItemSortBy.CommunityRating ||
+ o.OrderBy == ItemSortBy.CriticRating ||
+ o.OrderBy == ItemSortBy.Runtime))
{
return false;
}
diff --git a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs
index 5ce5fd4fa..d50f3d075 100644
--- a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs
+++ b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs
@@ -232,9 +232,9 @@ namespace MediaBrowser.Controller.Entities
public int? IndexNumber { get; set; }
- public int? MinParentalRating { get; set; }
+ public ParentalRatingScore? MinParentalRating { get; set; }
- public int? MaxParentalRating { get; set; }
+ public ParentalRatingScore? MaxParentalRating { get; set; }
public bool? HasDeadParentId { get; set; }
@@ -306,6 +306,8 @@ namespace MediaBrowser.Controller.Entities
public bool? IsDeadStudio { get; set; }
+ public bool? IsDeadGenre { get; set; }
+
public bool? IsDeadPerson { get; set; }
/// <summary>
@@ -360,16 +362,17 @@ namespace MediaBrowser.Controller.Entities
public void SetUser(User user)
{
- MaxParentalRating = user.MaxParentalAgeRating;
-
- if (MaxParentalRating.HasValue)
+ var maxRating = user.MaxParentalRatingScore;
+ if (maxRating.HasValue)
{
- string other = UnratedItem.Other.ToString();
- BlockUnratedItems = user.GetPreference(PreferenceKind.BlockUnratedItems)
- .Where(i => i != other)
- .Select(e => Enum.Parse<UnratedItem>(e, true)).ToArray();
+ MaxParentalRating = new(maxRating.Value, user.MaxParentalRatingSubScore);
}
+ var other = UnratedItem.Other.ToString();
+ BlockUnratedItems = user.GetPreference(PreferenceKind.BlockUnratedItems)
+ .Where(i => i != other)
+ .Select(e => Enum.Parse<UnratedItem>(e, true)).ToArray();
+
ExcludeInheritedTags = user.GetPreference(PreferenceKind.BlockedTags);
IncludeInheritedTags = user.GetPreference(PreferenceKind.AllowedTags);
diff --git a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs
index d656fccb4..dd5852823 100644
--- a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs
+++ b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs
@@ -197,7 +197,7 @@ namespace MediaBrowser.Controller.Entities.Movies
var expandedFolders = new List<Guid>();
return FlattenItems(this, expandedFolders)
- .SelectMany(i => LibraryManager.GetCollectionFolders(i))
+ .SelectMany(LibraryManager.GetCollectionFolders)
.Select(i => i.Id)
.Distinct()
.ToArray();
diff --git a/MediaBrowser.Controller/Entities/TV/Episode.cs b/MediaBrowser.Controller/Entities/TV/Episode.cs
index 46bad3f3b..6bdba36f9 100644
--- a/MediaBrowser.Controller/Entities/TV/Episode.cs
+++ b/MediaBrowser.Controller/Entities/TV/Episode.cs
@@ -7,12 +7,14 @@ using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.Json.Serialization;
+using System.Threading;
using Jellyfin.Data.Enums;
using Jellyfin.Extensions;
+using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Providers;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Entities.TV
@@ -22,6 +24,8 @@ namespace MediaBrowser.Controller.Entities.TV
/// </summary>
public class Episode : Video, IHasTrailers, IHasLookupInfo<EpisodeInfo>, IHasSeries
{
+ public static IMediaEncoder MediaEncoder { get; set; }
+
/// <inheritdoc />
[JsonIgnore]
public IReadOnlyList<BaseItem> LocalTrailers => GetExtras()
@@ -325,6 +329,39 @@ namespace MediaBrowser.Controller.Entities.TV
{
if (SourceType == SourceType.Library || SourceType == SourceType.LiveTV)
{
+ var libraryOptions = LibraryManager.GetLibraryOptions(this);
+ if (libraryOptions.EnableEmbeddedEpisodeInfos && string.Equals(Container, "mp4", StringComparison.OrdinalIgnoreCase))
+ {
+ try
+ {
+ var mediaInfo = MediaEncoder.GetMediaInfo(
+ new MediaInfoRequest
+ {
+ MediaSource = GetMediaSources(false)[0],
+ MediaType = DlnaProfileType.Video
+ },
+ CancellationToken.None).GetAwaiter().GetResult();
+ if (mediaInfo.ParentIndexNumber > 0)
+ {
+ ParentIndexNumber = mediaInfo.ParentIndexNumber;
+ }
+
+ if (mediaInfo.IndexNumber > 0)
+ {
+ IndexNumber = mediaInfo.IndexNumber;
+ }
+
+ if (!string.IsNullOrEmpty(mediaInfo.ShowName))
+ {
+ SeriesName = mediaInfo.ShowName;
+ }
+ }
+ catch (Exception ex)
+ {
+ Logger.LogError(ex, "Error reading the episode information with ffprobe. Episode: {EpisodeInfo}", Path);
+ }
+ }
+
try
{
if (LibraryManager.FillMissingEpisodeNumbersFromPath(this, replaceAllMetadata))
diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs
index b4ad05921..62c73d56f 100644
--- a/MediaBrowser.Controller/Entities/TV/Series.cs
+++ b/MediaBrowser.Controller/Entities/TV/Series.cs
@@ -214,7 +214,7 @@ namespace MediaBrowser.Controller.Entities.TV
query.AncestorWithPresentationUniqueKey = null;
query.SeriesPresentationUniqueKey = seriesKey;
query.IncludeItemTypes = new[] { BaseItemKind.Season };
- query.OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) };
+ query.OrderBy = new[] { (ItemSortBy.IndexNumber, SortOrder.Ascending) };
if (user is not null && !user.DisplayMissingEpisodes)
{
@@ -247,10 +247,6 @@ namespace MediaBrowser.Controller.Entities.TV
query.AncestorWithPresentationUniqueKey = null;
query.SeriesPresentationUniqueKey = seriesKey;
- if (query.OrderBy.Count == 0)
- {
- query.OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) };
- }
if (query.IncludeItemTypes.Length == 0)
{
diff --git a/MediaBrowser.Controller/Entities/UserViewBuilder.cs b/MediaBrowser.Controller/Entities/UserViewBuilder.cs
index c2b4da32a..1eb3c8f50 100644
--- a/MediaBrowser.Controller/Entities/UserViewBuilder.cs
+++ b/MediaBrowser.Controller/Entities/UserViewBuilder.cs
@@ -924,6 +924,11 @@ namespace MediaBrowser.Controller.Entities
}
}
+ if (query.ExcludeItemIds.Contains(item.Id))
+ {
+ return false;
+ }
+
return true;
}
diff --git a/MediaBrowser.Controller/IO/IExternalDataManager.cs b/MediaBrowser.Controller/IO/IExternalDataManager.cs
new file mode 100644
index 000000000..f69f4586c
--- /dev/null
+++ b/MediaBrowser.Controller/IO/IExternalDataManager.cs
@@ -0,0 +1,19 @@
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.Entities;
+
+namespace MediaBrowser.Controller.IO;
+
+/// <summary>
+/// Interface IPathManager.
+/// </summary>
+public interface IExternalDataManager
+{
+ /// <summary>
+ /// Deletes all external item data.
+ /// </summary>
+ /// <param name="item">The item.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Task.</returns>
+ Task DeleteExternalItemDataAsync(BaseItem item, CancellationToken cancellationToken);
+}
diff --git a/MediaBrowser.Controller/IO/IPathManager.cs b/MediaBrowser.Controller/IO/IPathManager.cs
index 036889810..eb6743754 100644
--- a/MediaBrowser.Controller/IO/IPathManager.cs
+++ b/MediaBrowser.Controller/IO/IPathManager.cs
@@ -1,9 +1,10 @@
+using System.Collections.Generic;
using MediaBrowser.Controller.Entities;
namespace MediaBrowser.Controller.IO;
/// <summary>
-/// Interface ITrickplayManager.
+/// Interface IPathManager.
/// </summary>
public interface IPathManager
{
@@ -14,4 +15,57 @@ public interface IPathManager
/// <param name="saveWithMedia">Whether or not the tile should be saved next to the media file.</param>
/// <returns>The absolute path.</returns>
public string GetTrickplayDirectory(BaseItem item, bool saveWithMedia = false);
+
+ /// <summary>
+ /// Gets the path to the subtitle file.
+ /// </summary>
+ /// <param name="mediaSourceId">The media source id.</param>
+ /// <param name="streamIndex">The stream index.</param>
+ /// <param name="extension">The subtitle file extension.</param>
+ /// <returns>The absolute path.</returns>
+ public string GetSubtitlePath(string mediaSourceId, int streamIndex, string extension);
+
+ /// <summary>
+ /// Gets the path to the subtitle file.
+ /// </summary>
+ /// <param name="mediaSourceId">The media source id.</param>
+ /// <returns>The absolute path.</returns>
+ public string GetSubtitleFolderPath(string mediaSourceId);
+
+ /// <summary>
+ /// Gets the path to the attachment file.
+ /// </summary>
+ /// <param name="mediaSourceId">The media source id.</param>
+ /// <param name="fileName">The attachmentFileName index.</param>
+ /// <returns>The absolute path.</returns>
+ public string GetAttachmentPath(string mediaSourceId, string fileName);
+
+ /// <summary>
+ /// Gets the path to the attachment folder.
+ /// </summary>
+ /// <param name="mediaSourceId">The media source id.</param>
+ /// <returns>The absolute path.</returns>
+ public string GetAttachmentFolderPath(string mediaSourceId);
+
+ /// <summary>
+ /// Gets the chapter images data path.
+ /// </summary>
+ /// <param name="item">The base item.</param>
+ /// <returns>The chapter images data path.</returns>
+ public string GetChapterImageFolderPath(BaseItem item);
+
+ /// <summary>
+ /// Gets the chapter images path.
+ /// </summary>
+ /// <param name="item">The base item.</param>
+ /// <param name="chapterPositionTicks">The chapter position.</param>
+ /// <returns>The chapter images data path.</returns>
+ public string GetChapterImagePath(BaseItem item, long chapterPositionTicks);
+
+ /// <summary>
+ /// Gets the paths of extracted data folders.
+ /// </summary>
+ /// <param name="item">The base item.</param>
+ /// <returns>The absolute paths.</returns>
+ public IReadOnlyList<string> GetExtractedDataPaths(BaseItem item);
}
diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs
index e9c4d9e19..b76141db0 100644
--- a/MediaBrowser.Controller/IServerApplicationHost.cs
+++ b/MediaBrowser.Controller/IServerApplicationHost.cs
@@ -39,6 +39,11 @@ namespace MediaBrowser.Controller
string FriendlyName { get; }
/// <summary>
+ /// Gets or sets the path to the backup archive used to restore upon restart.
+ /// </summary>
+ string RestoreBackupPath { get; set; }
+
+ /// <summary>
/// Gets a URL specific for the request.
/// </summary>
/// <param name="request">The <see cref="HttpRequest"/> instance.</param>
diff --git a/MediaBrowser.Controller/IServerApplicationPaths.cs b/MediaBrowser.Controller/IServerApplicationPaths.cs
index 608286cd8..a6e83a02c 100644
--- a/MediaBrowser.Controller/IServerApplicationPaths.cs
+++ b/MediaBrowser.Controller/IServerApplicationPaths.cs
@@ -2,6 +2,10 @@
#pragma warning disable CS1591
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
using MediaBrowser.Common.Configuration;
namespace MediaBrowser.Controller
diff --git a/MediaBrowser.Controller/ISystemManager.cs b/MediaBrowser.Controller/ISystemManager.cs
index ef3034d2f..08344a1e5 100644
--- a/MediaBrowser.Controller/ISystemManager.cs
+++ b/MediaBrowser.Controller/ISystemManager.cs
@@ -1,5 +1,6 @@
using MediaBrowser.Model.System;
using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
namespace MediaBrowser.Controller;
@@ -31,4 +32,10 @@ public interface ISystemManager
/// Starts the application shutdown process.
/// </summary>
void Shutdown();
+
+ /// <summary>
+ /// Gets the systems storage resources.
+ /// </summary>
+ /// <returns>The <see cref="SystemStorageInfo"/>.</returns>
+ SystemStorageInfo GetSystemStorageInfo();
}
diff --git a/MediaBrowser.Controller/Library/IKeyframeManager.cs b/MediaBrowser.Controller/Library/IKeyframeManager.cs
new file mode 100644
index 000000000..b0155efdd
--- /dev/null
+++ b/MediaBrowser.Controller/Library/IKeyframeManager.cs
@@ -0,0 +1,37 @@
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.MediaEncoding.Keyframes;
+
+namespace MediaBrowser.Controller.IO;
+
+/// <summary>
+/// Interface IKeyframeManager.
+/// </summary>
+public interface IKeyframeManager
+{
+ /// <summary>
+ /// Gets the keyframe data.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <returns>The keyframe data.</returns>
+ IReadOnlyList<KeyframeData> GetKeyframeData(Guid itemId);
+
+ /// <summary>
+ /// Saves the keyframe data.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="data">The keyframe data.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The task object representing the asynchronous operation.</returns>
+ Task SaveKeyframeDataAsync(Guid itemId, KeyframeData data, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Deletes the keyframe data.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The task object representing the asynchronous operation.</returns>
+ Task DeleteKeyframeDataAsync(Guid itemId, CancellationToken cancellationToken);
+}
diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs
index df90f546c..98ed15eb6 100644
--- a/MediaBrowser.Controller/Library/ILibraryManager.cs
+++ b/MediaBrowser.Controller/Library/ILibraryManager.cs
@@ -220,13 +220,13 @@ namespace MediaBrowser.Controller.Library
/// <param name="resolvers">The resolvers.</param>
/// <param name="introProviders">The intro providers.</param>
/// <param name="itemComparers">The item comparers.</param>
- /// <param name="postscanTasks">The postscan tasks.</param>
+ /// <param name="postScanTasks">The post scan tasks.</param>
void AddParts(
IEnumerable<IResolverIgnoreRule> rules,
IEnumerable<IItemResolver> resolvers,
IEnumerable<IIntroProvider> introProviders,
IEnumerable<IBaseItemComparer> itemComparers,
- IEnumerable<ILibraryPostScanTask> postscanTasks);
+ IEnumerable<ILibraryPostScanTask> postScanTasks);
/// <summary>
/// Sorts the specified items.
@@ -593,11 +593,11 @@ namespace MediaBrowser.Controller.Library
QueryResult<BaseItem> GetItemsResult(InternalItemsQuery query);
/// <summary>
- /// Ignores the file.
+ /// Checks if the file is ignored.
/// </summary>
/// <param name="file">The file.</param>
/// <param name="parent">The parent.</param>
- /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
+ /// <returns><c>true</c> if ignored, <c>false</c> otherwise.</returns>
bool IgnoreFile(FileSystemMetadata file, BaseItem parent);
Guid GetStudioId(string name);
diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj
index d8aaf5ba0..3353ad63f 100644
--- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj
+++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj
@@ -28,6 +28,7 @@
<ProjectReference Include="../Emby.Naming/Emby.Naming.csproj" />
<ProjectReference Include="../MediaBrowser.Model/MediaBrowser.Model.csproj" />
<ProjectReference Include="../MediaBrowser.Common/MediaBrowser.Common.csproj" />
+ <ProjectReference Include="../src/Jellyfin.MediaEncoding.Keyframes/Jellyfin.MediaEncoding.Keyframes.csproj" />
</ItemGroup>
<ItemGroup>
diff --git a/MediaBrowser.Controller/MediaEncoding/BitStreamFilterOptionType.cs b/MediaBrowser.Controller/MediaEncoding/BitStreamFilterOptionType.cs
new file mode 100644
index 000000000..41d21e440
--- /dev/null
+++ b/MediaBrowser.Controller/MediaEncoding/BitStreamFilterOptionType.cs
@@ -0,0 +1,32 @@
+namespace MediaBrowser.Controller.MediaEncoding;
+
+/// <summary>
+/// Enum BitStreamFilterOptionType.
+/// </summary>
+public enum BitStreamFilterOptionType
+{
+ /// <summary>
+ /// hevc_metadata bsf with remove_dovi option.
+ /// </summary>
+ HevcMetadataRemoveDovi = 0,
+
+ /// <summary>
+ /// hevc_metadata bsf with remove_hdr10plus option.
+ /// </summary>
+ HevcMetadataRemoveHdr10Plus = 1,
+
+ /// <summary>
+ /// av1_metadata bsf with remove_dovi option.
+ /// </summary>
+ Av1MetadataRemoveDovi = 2,
+
+ /// <summary>
+ /// av1_metadata bsf with remove_hdr10plus option.
+ /// </summary>
+ Av1MetadataRemoveHdr10Plus = 3,
+
+ /// <summary>
+ /// dovi_rpu bsf with strip option.
+ /// </summary>
+ DoviRpuStrip = 4,
+}
diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
index 8fcbba738..364470cd2 100644
--- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
+++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
@@ -19,6 +19,7 @@ using Jellyfin.Database.Implementations.Enums;
using Jellyfin.Extensions;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Extensions;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
@@ -37,7 +38,13 @@ namespace MediaBrowser.Controller.MediaEncoding
/// periods, underscores, commas, and vertical bars, with a length between 0 and 40 characters.
/// This should matches all common valid codecs.
/// </summary>
- public const string ValidationRegex = @"^[a-zA-Z0-9\-\._,|]{0,40}$";
+ public const string ContainerValidationRegex = @"^[a-zA-Z0-9\-\._,|]{0,40}$";
+
+ /// <summary>
+ /// The level validation regex.
+ /// This regular expression matches strings representing a double.
+ /// </summary>
+ public const string LevelValidationRegex = @"-?[0-9]+(?:\.[0-9]+)?";
private const string _defaultMjpegEncoder = "mjpeg";
@@ -55,6 +62,7 @@ namespace MediaBrowser.Controller.MediaEncoding
private readonly ISubtitleEncoder _subtitleEncoder;
private readonly IConfiguration _config;
private readonly IConfigurationManager _configurationManager;
+ private readonly IPathManager _pathManager;
// i915 hang was fixed by linux 6.2 (3f882f2)
private readonly Version _minKerneli915Hang = new Version(5, 18);
@@ -76,8 +84,9 @@ namespace MediaBrowser.Controller.MediaEncoding
private readonly Version _minFFmpegQsvVppOutRangeOption = new Version(7, 0, 1);
private readonly Version _minFFmpegVaapiDeviceVendorId = new Version(7, 0, 1);
private readonly Version _minFFmpegQsvVppScaleModeOption = new Version(6, 0);
+ private readonly Version _minFFmpegRkmppHevcDecDoviRpu = new Version(7, 1, 1);
- private static readonly Regex _validationRegex = new(ValidationRegex, RegexOptions.Compiled);
+ private static readonly Regex _containerValidationRegex = new(ContainerValidationRegex, RegexOptions.Compiled);
private static readonly string[] _videoProfilesH264 =
[
@@ -153,13 +162,22 @@ namespace MediaBrowser.Controller.MediaEncoding
IMediaEncoder mediaEncoder,
ISubtitleEncoder subtitleEncoder,
IConfiguration config,
- IConfigurationManager configurationManager)
+ IConfigurationManager configurationManager,
+ IPathManager pathManager)
{
_appPaths = appPaths;
_mediaEncoder = mediaEncoder;
_subtitleEncoder = subtitleEncoder;
_config = config;
_configurationManager = configurationManager;
+ _pathManager = pathManager;
+ }
+
+ private enum DynamicHdrMetadataRemovalPlan
+ {
+ None,
+ RemoveDovi,
+ RemoveHdr10Plus,
}
[GeneratedRegex(@"\s+")]
@@ -332,8 +350,17 @@ namespace MediaBrowser.Controller.MediaEncoding
if (state.VideoStream.VideoRange == VideoRange.HDR
&& state.VideoStream.VideoRangeType == VideoRangeType.DOVI)
{
- // Only native SW decoder and HW accelerator can parse dovi rpu.
+ // Only native SW decoder, HW accelerator and hevc_rkmpp decoder can parse dovi rpu.
var vidDecoder = GetHardwareVideoDecoder(state, options) ?? string.Empty;
+
+ var isRkmppDecoder = vidDecoder.Contains("rkmpp", StringComparison.OrdinalIgnoreCase);
+ if (isRkmppDecoder
+ && _mediaEncoder.EncoderVersion >= _minFFmpegRkmppHevcDecDoviRpu
+ && string.Equals(state.VideoStream?.Codec, "hevc", StringComparison.OrdinalIgnoreCase))
+ {
+ return true;
+ }
+
var isSwDecoder = string.IsNullOrEmpty(vidDecoder);
var isNvdecDecoder = vidDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase);
var isVaapiDecoder = vidDecoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase);
@@ -342,11 +369,8 @@ namespace MediaBrowser.Controller.MediaEncoding
return isSwDecoder || isNvdecDecoder || isVaapiDecoder || isD3d11vaDecoder || isVideoToolBoxDecoder;
}
- return state.VideoStream.VideoRange == VideoRange.HDR
- && (state.VideoStream.VideoRangeType == VideoRangeType.HDR10
- || state.VideoStream.VideoRangeType == VideoRangeType.HLG
- || state.VideoStream.VideoRangeType == VideoRangeType.DOVIWithHDR10
- || state.VideoStream.VideoRangeType == VideoRangeType.DOVIWithHLG);
+ // GPU tonemapping supports all HDR RangeTypes
+ return state.VideoStream.VideoRange == VideoRange.HDR;
}
private bool IsVulkanHwTonemapAvailable(EncodingJobInfo state, EncodingOptions options)
@@ -381,8 +405,7 @@ namespace MediaBrowser.Controller.MediaEncoding
}
return state.VideoStream.VideoRange == VideoRange.HDR
- && (state.VideoStream.VideoRangeType == VideoRangeType.HDR10
- || state.VideoStream.VideoRangeType == VideoRangeType.DOVIWithHDR10);
+ && IsDoviWithHdr10Bl(state.VideoStream);
}
private bool IsVideoToolboxTonemapAvailable(EncodingJobInfo state, EncodingOptions options)
@@ -397,7 +420,8 @@ namespace MediaBrowser.Controller.MediaEncoding
// Certain DV profile 5 video works in Safari with direct playing, but the VideoToolBox does not produce correct mapping results with transcoding.
// All other HDR formats working.
return state.VideoStream.VideoRange == VideoRange.HDR
- && state.VideoStream.VideoRangeType is VideoRangeType.HDR10 or VideoRangeType.HLG or VideoRangeType.HDR10Plus or VideoRangeType.DOVIWithHDR10 or VideoRangeType.DOVIWithHLG;
+ && (IsDoviWithHdr10Bl(state.VideoStream)
+ || state.VideoStream.VideoRangeType is VideoRangeType.HLG);
}
private bool IsVideoStreamHevcRext(EncodingJobInfo state)
@@ -452,7 +476,7 @@ namespace MediaBrowser.Controller.MediaEncoding
return GetMjpegEncoder(state, encodingOptions);
}
- if (_validationRegex.IsMatch(codec))
+ if (_containerValidationRegex.IsMatch(codec))
{
return codec.ToLowerInvariant();
}
@@ -493,7 +517,7 @@ namespace MediaBrowser.Controller.MediaEncoding
public static string GetInputFormat(string container)
{
- if (string.IsNullOrEmpty(container) || !_validationRegex.IsMatch(container))
+ if (string.IsNullOrEmpty(container) || !_containerValidationRegex.IsMatch(container))
{
return null;
}
@@ -711,7 +735,7 @@ namespace MediaBrowser.Controller.MediaEncoding
{
var codec = state.OutputAudioCodec;
- if (!_validationRegex.IsMatch(codec))
+ if (!_containerValidationRegex.IsMatch(codec))
{
codec = "aac";
}
@@ -1301,6 +1325,13 @@ namespace MediaBrowser.Controller.MediaEncoding
|| codec.Contains("hevc", StringComparison.OrdinalIgnoreCase);
}
+ public static bool IsAv1(MediaStream stream)
+ {
+ var codec = stream.Codec ?? string.Empty;
+
+ return codec.Contains("av1", StringComparison.OrdinalIgnoreCase);
+ }
+
public static bool IsAAC(MediaStream stream)
{
var codec = stream.Codec ?? string.Empty;
@@ -1308,8 +1339,125 @@ namespace MediaBrowser.Controller.MediaEncoding
return codec.Contains("aac", StringComparison.OrdinalIgnoreCase);
}
- public static string GetBitStreamArgs(MediaStream stream)
+ public static bool IsDoviWithHdr10Bl(MediaStream stream)
+ {
+ var rangeType = stream?.VideoRangeType;
+
+ return rangeType is VideoRangeType.DOVIWithHDR10
+ or VideoRangeType.DOVIWithEL
+ or VideoRangeType.DOVIWithHDR10Plus
+ or VideoRangeType.DOVIWithELHDR10Plus
+ or VideoRangeType.DOVIInvalid;
+ }
+
+ public static bool IsDovi(MediaStream stream)
+ {
+ var rangeType = stream?.VideoRangeType;
+
+ return IsDoviWithHdr10Bl(stream)
+ || (rangeType is VideoRangeType.DOVI
+ or VideoRangeType.DOVIWithHLG
+ or VideoRangeType.DOVIWithSDR);
+ }
+
+ public static bool IsHdr10Plus(MediaStream stream)
+ {
+ var rangeType = stream?.VideoRangeType;
+
+ return rangeType is VideoRangeType.HDR10Plus
+ or VideoRangeType.DOVIWithHDR10Plus
+ or VideoRangeType.DOVIWithELHDR10Plus;
+ }
+
+ /// <summary>
+ /// Check if dynamic HDR metadata should be removed during stream copy.
+ /// Please note this check assumes the range check has already been done
+ /// and trivial fallbacks like HDR10+ to HDR10, DOVIWithHDR10 to HDR10 is already checked.
+ /// </summary>
+ private static DynamicHdrMetadataRemovalPlan ShouldRemoveDynamicHdrMetadata(EncodingJobInfo state)
{
+ var videoStream = state.VideoStream;
+ if (videoStream.VideoRange is not VideoRange.HDR)
+ {
+ return DynamicHdrMetadataRemovalPlan.None;
+ }
+
+ var requestedRangeTypes = state.GetRequestedRangeTypes(state.VideoStream.Codec);
+ if (requestedRangeTypes.Length == 0)
+ {
+ return DynamicHdrMetadataRemovalPlan.None;
+ }
+
+ var requestHasHDR10 = requestedRangeTypes.Contains(VideoRangeType.HDR10.ToString(), StringComparison.OrdinalIgnoreCase);
+ var requestHasDOVI = requestedRangeTypes.Contains(VideoRangeType.DOVI.ToString(), StringComparison.OrdinalIgnoreCase);
+ var requestHasDOVIwithEL = requestedRangeTypes.Contains(VideoRangeType.DOVIWithEL.ToString(), StringComparison.OrdinalIgnoreCase);
+ var requestHasDOVIwithELHDR10plus = requestedRangeTypes.Contains(VideoRangeType.DOVIWithELHDR10Plus.ToString(), StringComparison.OrdinalIgnoreCase);
+
+ var shouldRemoveHdr10Plus = false;
+ // Case 1: Client supports HDR10, does not support DOVI with EL but EL presets
+ var shouldRemoveDovi = (!requestHasDOVIwithEL && requestHasHDR10) && videoStream.VideoRangeType == VideoRangeType.DOVIWithEL;
+
+ // Case 2: Client supports DOVI, does not support broken DOVI config
+ // Client does not report DOVI support should be allowed to copy bad data for remuxing as HDR10 players would not crash
+ shouldRemoveDovi = shouldRemoveDovi || (requestHasDOVI && videoStream.VideoRangeType == VideoRangeType.DOVIInvalid);
+
+ // Special case: we have a video with both EL and HDR10+
+ // If the client supports EL but not in the case of coexistence with HDR10+, remove HDR10+ for compatibility reasons.
+ // Otherwise, remove DOVI if the client is not a DOVI player
+ if (videoStream.VideoRangeType == VideoRangeType.DOVIWithELHDR10Plus)
+ {
+ shouldRemoveHdr10Plus = requestHasDOVIwithEL && !requestHasDOVIwithELHDR10plus;
+ shouldRemoveDovi = shouldRemoveDovi || !shouldRemoveHdr10Plus;
+ }
+
+ if (shouldRemoveDovi)
+ {
+ return DynamicHdrMetadataRemovalPlan.RemoveDovi;
+ }
+
+ // If the client is a Dolby Vision Player, remove the HDR10+ metadata to avoid playback issues
+ shouldRemoveHdr10Plus = shouldRemoveHdr10Plus || (requestHasDOVI && videoStream.VideoRangeType == VideoRangeType.DOVIWithHDR10Plus);
+ return shouldRemoveHdr10Plus ? DynamicHdrMetadataRemovalPlan.RemoveHdr10Plus : DynamicHdrMetadataRemovalPlan.None;
+ }
+
+ private bool CanEncoderRemoveDynamicHdrMetadata(DynamicHdrMetadataRemovalPlan plan, MediaStream videoStream)
+ {
+ return plan switch
+ {
+ DynamicHdrMetadataRemovalPlan.RemoveDovi => _mediaEncoder.SupportsBitStreamFilterWithOption(BitStreamFilterOptionType.DoviRpuStrip)
+ || (IsH265(videoStream) && _mediaEncoder.SupportsBitStreamFilterWithOption(BitStreamFilterOptionType.HevcMetadataRemoveDovi))
+ || (IsAv1(videoStream) && _mediaEncoder.SupportsBitStreamFilterWithOption(BitStreamFilterOptionType.Av1MetadataRemoveDovi)),
+ DynamicHdrMetadataRemovalPlan.RemoveHdr10Plus => (IsH265(videoStream) && _mediaEncoder.SupportsBitStreamFilterWithOption(BitStreamFilterOptionType.HevcMetadataRemoveHdr10Plus))
+ || (IsAv1(videoStream) && _mediaEncoder.SupportsBitStreamFilterWithOption(BitStreamFilterOptionType.Av1MetadataRemoveHdr10Plus)),
+ _ => true,
+ };
+ }
+
+ public bool IsDoviRemoved(EncodingJobInfo state)
+ {
+ return state?.VideoStream is not null && ShouldRemoveDynamicHdrMetadata(state) == DynamicHdrMetadataRemovalPlan.RemoveDovi
+ && CanEncoderRemoveDynamicHdrMetadata(DynamicHdrMetadataRemovalPlan.RemoveDovi, state.VideoStream);
+ }
+
+ public bool IsHdr10PlusRemoved(EncodingJobInfo state)
+ {
+ return state?.VideoStream is not null && ShouldRemoveDynamicHdrMetadata(state) == DynamicHdrMetadataRemovalPlan.RemoveHdr10Plus
+ && CanEncoderRemoveDynamicHdrMetadata(DynamicHdrMetadataRemovalPlan.RemoveHdr10Plus, state.VideoStream);
+ }
+
+ public string GetBitStreamArgs(EncodingJobInfo state, MediaStreamType streamType)
+ {
+ if (state is null)
+ {
+ return null;
+ }
+
+ var stream = streamType switch
+ {
+ MediaStreamType.Audio => state.AudioStream,
+ MediaStreamType.Video => state.VideoStream,
+ _ => state.VideoStream
+ };
// TODO This is auto inserted into the mpegts mux so it might not be needed.
// https://www.ffmpeg.org/ffmpeg-bitstream-filters.html#h264_005fmp4toannexb
if (IsH264(stream))
@@ -1317,21 +1465,57 @@ namespace MediaBrowser.Controller.MediaEncoding
return "-bsf:v h264_mp4toannexb";
}
+ if (IsAAC(stream))
+ {
+ // Convert adts header(mpegts) to asc header(mp4).
+ return "-bsf:a aac_adtstoasc";
+ }
+
if (IsH265(stream))
{
- return "-bsf:v hevc_mp4toannexb";
+ var filter = "-bsf:v hevc_mp4toannexb";
+
+ // The following checks are not complete because the copy would be rejected
+ // if the encoder cannot remove required metadata.
+ // And if bsf is used, we must already be using copy codec.
+ switch (ShouldRemoveDynamicHdrMetadata(state))
+ {
+ default:
+ case DynamicHdrMetadataRemovalPlan.None:
+ break;
+ case DynamicHdrMetadataRemovalPlan.RemoveDovi:
+ filter += _mediaEncoder.SupportsBitStreamFilterWithOption(BitStreamFilterOptionType.HevcMetadataRemoveDovi)
+ ? ",hevc_metadata=remove_dovi=1"
+ : ",dovi_rpu=strip=1";
+ break;
+ case DynamicHdrMetadataRemovalPlan.RemoveHdr10Plus:
+ filter += ",hevc_metadata=remove_hdr10plus=1";
+ break;
+ }
+
+ return filter;
}
- if (IsAAC(stream))
+ if (IsAv1(stream))
{
- // Convert adts header(mpegts) to asc header(mp4).
- return "-bsf:a aac_adtstoasc";
+ switch (ShouldRemoveDynamicHdrMetadata(state))
+ {
+ default:
+ case DynamicHdrMetadataRemovalPlan.None:
+ return null;
+ case DynamicHdrMetadataRemovalPlan.RemoveDovi:
+ return _mediaEncoder.SupportsBitStreamFilterWithOption(BitStreamFilterOptionType.Av1MetadataRemoveDovi)
+ ? "-bsf:v av1_metadata=remove_dovi=1"
+ : "-bsf:v dovi_rpu=strip=1";
+ case DynamicHdrMetadataRemovalPlan.RemoveHdr10Plus:
+ return "-bsf:v av1_metadata=remove_hdr10plus=1";
+ }
}
return null;
}
- public static string GetAudioBitStreamArguments(EncodingJobInfo state, string segmentContainer, string mediaSourceContainer)
+ public string GetAudioBitStreamArguments(EncodingJobInfo state, string segmentContainer, string mediaSourceContainer)
{
var bitStreamArgs = string.Empty;
var segmentFormat = GetSegmentFileExtension(segmentContainer).TrimStart('.');
@@ -1342,7 +1526,7 @@ namespace MediaBrowser.Controller.MediaEncoding
|| string.Equals(mediaSourceContainer, "aac", StringComparison.OrdinalIgnoreCase)
|| string.Equals(mediaSourceContainer, "hls", StringComparison.OrdinalIgnoreCase)))
{
- bitStreamArgs = GetBitStreamArgs(state.AudioStream);
+ bitStreamArgs = GetBitStreamArgs(state, MediaStreamType.Audio);
bitStreamArgs = string.IsNullOrEmpty(bitStreamArgs) ? string.Empty : " " + bitStreamArgs;
}
@@ -1388,6 +1572,26 @@ namespace MediaBrowser.Controller.MediaEncoding
return FormattableString.Invariant($" -maxrate {bitrate} -bufsize {bufsize}");
}
+ if (string.Equals(videoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoCodec, "hevc_qsv", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoCodec, "av1_qsv", StringComparison.OrdinalIgnoreCase))
+ {
+ // TODO: probe QSV encoders' capabilities and enable more tuning options
+ // See also https://github.com/intel/media-delivery/blob/master/doc/quality.rst
+
+ // Enable MacroBlock level bitrate control for better subjective visual quality
+ var mbbrcOpt = string.Empty;
+ if (string.Equals(videoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoCodec, "hevc_qsv", StringComparison.OrdinalIgnoreCase))
+ {
+ mbbrcOpt = " -mbbrc 1";
+ }
+
+ // Set (maxrate == bitrate + 1) to trigger VBR for better bitrate allocation
+ // Set (rc_init_occupancy == 2 * bitrate) and (bufsize == 4 * bitrate) to deal with drastic scene changes
+ return FormattableString.Invariant($"{mbbrcOpt} -b:v {bitrate} -maxrate {bitrate + 1} -rc_init_occupancy {bitrate * 2} -bufsize {bitrate * 4}");
+ }
+
if (string.Equals(videoCodec, "h264_amf", StringComparison.OrdinalIgnoreCase)
|| string.Equals(videoCodec, "hevc_amf", StringComparison.OrdinalIgnoreCase)
|| string.Equals(videoCodec, "av1_amf", StringComparison.OrdinalIgnoreCase))
@@ -1621,7 +1825,7 @@ namespace MediaBrowser.Controller.MediaEncoding
var alphaParam = enableAlpha ? ":alpha=1" : string.Empty;
var sub2videoParam = enableSub2video ? ":sub2video=1" : string.Empty;
- var fontPath = Path.Combine(_appPaths.CachePath, "attachments", state.MediaSource.Id);
+ var fontPath = _pathManager.GetAttachmentFolderPath(state.MediaSource.Id);
var fontParam = string.Format(
CultureInfo.InvariantCulture,
":fontsdir='{0}'",
@@ -2169,7 +2373,6 @@ namespace MediaBrowser.Controller.MediaEncoding
}
// DOVIWithHDR10 should be compatible with HDR10 supporting players. Same goes with HLG and of course SDR. So allow copy of those formats
-
var requestHasHDR10 = requestedRangeTypes.Contains(VideoRangeType.HDR10.ToString(), StringComparison.OrdinalIgnoreCase);
var requestHasHLG = requestedRangeTypes.Contains(VideoRangeType.HLG.ToString(), StringComparison.OrdinalIgnoreCase);
var requestHasSDR = requestedRangeTypes.Contains(VideoRangeType.SDR.ToString(), StringComparison.OrdinalIgnoreCase);
@@ -2177,9 +2380,17 @@ namespace MediaBrowser.Controller.MediaEncoding
if (!requestedRangeTypes.Contains(videoStream.VideoRangeType.ToString(), StringComparison.OrdinalIgnoreCase)
&& !((requestHasHDR10 && videoStream.VideoRangeType == VideoRangeType.DOVIWithHDR10)
|| (requestHasHLG && videoStream.VideoRangeType == VideoRangeType.DOVIWithHLG)
- || (requestHasSDR && videoStream.VideoRangeType == VideoRangeType.DOVIWithSDR)))
- {
- return false;
+ || (requestHasSDR && videoStream.VideoRangeType == VideoRangeType.DOVIWithSDR)
+ || (requestHasHDR10 && videoStream.VideoRangeType == VideoRangeType.HDR10Plus)))
+ {
+ // Check complicated cases where we need to remove dynamic metadata
+ // Conservatively refuse to copy if the encoder can't remove dynamic metadata,
+ // but a removal is required for compatability reasons.
+ var dynamicHdrMetadataRemovalPlan = ShouldRemoveDynamicHdrMetadata(state);
+ if (!CanEncoderRemoveDynamicHdrMetadata(dynamicHdrMetadataRemovalPlan, videoStream))
+ {
+ return false;
+ }
}
}
@@ -2691,10 +2902,10 @@ namespace MediaBrowser.Controller.MediaEncoding
var seekTick = isHlsRemuxing ? time + 5000000L : time;
// Seeking beyond EOF makes no sense in transcoding. Clamp the seekTick value to
- // [0, RuntimeTicks - 0.5s], so that the muxer gets packets and avoid error codes.
+ // [0, RuntimeTicks - 5.0s], so that the muxer gets packets and avoid error codes.
if (maxTime > 0)
{
- seekTick = Math.Clamp(seekTick, 0, Math.Max(maxTime - 5000000L, 0));
+ seekTick = Math.Clamp(seekTick, 0, Math.Max(maxTime - 50000000L, 0));
}
seekParam += string.Format(CultureInfo.InvariantCulture, "-ss {0}", _mediaEncoder.GetTimeParameter(seekTick));
@@ -3280,6 +3491,21 @@ namespace MediaBrowser.Controller.MediaEncoding
doubleRateDeint ? "1" : "0");
}
+ if (hwDeintSuffix.Contains("opencl", StringComparison.OrdinalIgnoreCase))
+ {
+ var useBwdif = options.DeinterlaceMethod == DeinterlaceMethod.bwdif;
+
+ if (_mediaEncoder.SupportsFilter("yadif_opencl")
+ && _mediaEncoder.SupportsFilter("bwdif_opencl"))
+ {
+ return string.Format(
+ CultureInfo.InvariantCulture,
+ "{0}_opencl={1}:-1:0",
+ useBwdif ? "bwdif" : "yadif",
+ doubleRateDeint ? "1" : "0");
+ }
+ }
+
if (hwDeintSuffix.Contains("vaapi", StringComparison.OrdinalIgnoreCase))
{
return string.Format(
@@ -3756,6 +3982,7 @@ namespace MediaBrowser.Controller.MediaEncoding
{
if (hasSubs)
{
+ var alphaFormatOpt = string.Empty;
if (hasGraphicalSubs)
{
var subPreProcFilters = GetGraphicalSubPreProcessFilters(swpInW, swpInH, subW, subH, reqW, reqH, reqMaxW, reqMaxH);
@@ -3773,10 +4000,13 @@ namespace MediaBrowser.Controller.MediaEncoding
subFilters.Add(alphaSrcFilter);
subFilters.Add("format=yuva420p");
subFilters.Add(subTextSubtitlesFilter);
+
+ alphaFormatOpt = _mediaEncoder.SupportsFilterWithOption(FilterOptionType.OverlayCudaAlphaFormat)
+ ? ":alpha_format=premultiplied" : string.Empty;
}
subFilters.Add("hwupload=derive_device=cuda");
- overlayFilters.Add("overlay_cuda=eof_action=pass:repeatlast=0");
+ overlayFilters.Add($"overlay_cuda=eof_action=pass:repeatlast=0{alphaFormatOpt}");
}
}
else
@@ -3908,7 +4138,12 @@ namespace MediaBrowser.Controller.MediaEncoding
// map from d3d11va to opencl via d3d11-opencl interop.
mainFilters.Add("hwmap=derive_device=opencl:mode=read");
- // hw deint <= TODO: finish the 'yadif_opencl' filter
+ // hw deint
+ if (doDeintH2645)
+ {
+ var deintFilter = GetHwDeinterlaceFilter(state, options, "opencl");
+ mainFilters.Add(deintFilter);
+ }
// hw transpose
if (doOclTranspose)
@@ -3973,6 +4208,7 @@ namespace MediaBrowser.Controller.MediaEncoding
{
if (hasSubs)
{
+ var alphaFormatOpt = string.Empty;
if (hasGraphicalSubs)
{
var subPreProcFilters = GetGraphicalSubPreProcessFilters(swpInW, swpInH, subW, subH, reqW, reqH, reqMaxW, reqMaxH);
@@ -3990,10 +4226,13 @@ namespace MediaBrowser.Controller.MediaEncoding
subFilters.Add(alphaSrcFilter);
subFilters.Add("format=yuva420p");
subFilters.Add(subTextSubtitlesFilter);
+
+ alphaFormatOpt = _mediaEncoder.SupportsFilterWithOption(FilterOptionType.OverlayOpenclAlphaFormat)
+ ? ":alpha_format=premultiplied" : string.Empty;
}
subFilters.Add("hwupload=derive_device=opencl");
- overlayFilters.Add("overlay_opencl=eof_action=pass:repeatlast=0");
+ overlayFilters.Add($"overlay_opencl=eof_action=pass:repeatlast=0{alphaFormatOpt}");
overlayFilters.Add("hwmap=derive_device=d3d11va:mode=write:reverse=1");
overlayFilters.Add("format=d3d11");
}
@@ -5621,7 +5860,7 @@ namespace MediaBrowser.Controller.MediaEncoding
var doDeintH2645 = doDeintH264 || doDeintHevc;
var doOclTonemap = IsHwTonemapAvailable(state, options);
- var hasSubs = state.SubtitleStream != null && ShouldEncodeSubtitle(state);
+ var hasSubs = state.SubtitleStream is not null && ShouldEncodeSubtitle(state);
var hasTextSubs = hasSubs && state.SubtitleStream.IsTextSubtitleStream;
var hasGraphicalSubs = hasSubs && !state.SubtitleStream.IsTextSubtitleStream;
var hasAssSubs = hasSubs
@@ -5701,7 +5940,7 @@ namespace MediaBrowser.Controller.MediaEncoding
// Use NV15 instead of P010 to avoid the issue.
// SDR inputs are using BGRA formats already which is not affected.
var intermediateFormat = string.Equals(outFormat, "p010", StringComparison.OrdinalIgnoreCase) ? "nv15" : outFormat;
- var hwScaleFilterFirstPass = $"scale_rkrga=w=iw/7.9:h=ih/7.9:format={intermediateFormat}:force_divisible_by=4:afbc=1";
+ var hwScaleFilterFirstPass = $"scale_rkrga=w=iw/7.9:h=ih/7.9:format={intermediateFormat}:force_original_aspect_ratio=increase:force_divisible_by=4:afbc=1";
mainFilters.Add(hwScaleFilterFirstPass);
}
@@ -5779,9 +6018,10 @@ namespace MediaBrowser.Controller.MediaEncoding
{
if (hasSubs)
{
+ var subMaxH = 1080;
if (hasGraphicalSubs)
{
- var subPreProcFilters = GetGraphicalSubPreProcessFilters(swpInW, swpInH, subW, subH, reqW, reqH, reqMaxW, reqMaxH);
+ var subPreProcFilters = GetGraphicalSubPreProcessFilters(swpInW, swpInH, subW, subH, reqW, reqH, reqMaxW, subMaxH);
subFilters.Add(subPreProcFilters);
subFilters.Add("format=bgra");
}
@@ -5791,7 +6031,7 @@ namespace MediaBrowser.Controller.MediaEncoding
var subFramerate = hasAssSubs ? Math.Min(framerate ?? 25, 60) : 10;
// alphasrc=s=1280x720:r=10:start=0,format=bgra,subtitles,hwupload
- var alphaSrcFilter = GetAlphaSrcFilter(state, swpInW, swpInH, reqW, reqH, reqMaxW, reqMaxH, subFramerate);
+ var alphaSrcFilter = GetAlphaSrcFilter(state, swpInW, swpInH, reqW, reqH, reqMaxW, subMaxH, subFramerate);
var subTextSubtitlesFilter = GetTextSubtitlesFilter(state, true, true);
subFilters.Add(alphaSrcFilter);
subFilters.Add("format=bgra");
@@ -5800,6 +6040,13 @@ namespace MediaBrowser.Controller.MediaEncoding
subFilters.Add("hwupload=derive_device=rkmpp");
+ // offload 1080p+ subtitles swscale upscaling from CPU to RGA
+ var (overlayW, overlayH) = GetFixedOutputSize(swpInW, swpInH, reqW, reqH, reqMaxW, reqMaxH);
+ if (overlayW.HasValue && overlayH.HasValue && overlayH.Value > subMaxH)
+ {
+ subFilters.Add($"vpp_rkrga=w={overlayW.Value}:h={overlayH.Value}:format=bgra:afbc=1");
+ }
+
// try enabling AFBC to save DDR bandwidth
var hwOverlayFilter = "overlay_rkrga=eof_action=pass:repeatlast=0:format=nv12";
if (isEncoderSupportAfbc)
@@ -6621,6 +6868,7 @@ namespace MediaBrowser.Controller.MediaEncoding
|| string.Equals("yuv420p12le", videoStream.PixelFormat, StringComparison.OrdinalIgnoreCase)
|| string.Equals("yuv422p12le", videoStream.PixelFormat, StringComparison.OrdinalIgnoreCase)
|| string.Equals("yuv444p12le", videoStream.PixelFormat, StringComparison.OrdinalIgnoreCase);
+ var isAv1SupportedSwFormatsVt = is8_10bitSwFormatsVt || string.Equals("yuv420p12le", videoStream.PixelFormat, StringComparison.OrdinalIgnoreCase);
// The related patches make videotoolbox hardware surface working is only available in jellyfin-ffmpeg 7.0.1 at the moment.
bool useHwSurface = (_mediaEncoder.EncoderVersion >= _minFFmpegWorkingVtHwSurface) && IsVideoToolboxFullSupported();
@@ -6654,6 +6902,13 @@ namespace MediaBrowser.Controller.MediaEncoding
{
return GetHwaccelType(state, options, "hevc", bitDepth, useHwSurface);
}
+
+ if (string.Equals("av1", videoStream.Codec, StringComparison.OrdinalIgnoreCase)
+ && isAv1SupportedSwFormatsVt
+ && _mediaEncoder.IsVideoToolboxAv1DecodeAvailable)
+ {
+ return GetHwaccelType(state, options, "av1", bitDepth, useHwSurface);
+ }
}
return null;
@@ -6748,7 +7003,8 @@ namespace MediaBrowser.Controller.MediaEncoding
if (string.Equals(videoStream.Codec, "av1", StringComparison.OrdinalIgnoreCase))
{
- return GetHwaccelType(state, options, "av1", bitDepth, hwSurface);
+ var accelType = GetHwaccelType(state, options, "av1", bitDepth, hwSurface);
+ return accelType + ((!string.IsNullOrEmpty(accelType) && isAfbcSupported) ? " -afbc rga" : string.Empty);
}
}
@@ -6982,7 +7238,7 @@ namespace MediaBrowser.Controller.MediaEncoding
state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
state.ReadInputAtNativeFramerate = mediaSource.ReadAtNativeFramerate;
- if (state.ReadInputAtNativeFramerate
+ if ((state.ReadInputAtNativeFramerate && !state.IsSegmentedLiveStream)
|| (mediaSource.Protocol == MediaProtocol.File
&& string.Equals(mediaSource.Container, "wtv", StringComparison.OrdinalIgnoreCase)))
{
@@ -7236,7 +7492,7 @@ namespace MediaBrowser.Controller.MediaEncoding
&& string.Equals(state.OutputContainer, "ts", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
{
- string bitStreamArgs = GetBitStreamArgs(state.VideoStream);
+ string bitStreamArgs = GetBitStreamArgs(state, MediaStreamType.Video);
if (!string.IsNullOrEmpty(bitStreamArgs))
{
args += " " + bitStreamArgs;
diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs
index 7586ac902..8d6211051 100644
--- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs
+++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs
@@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
+using System.ComponentModel;
using System.Globalization;
using System.Linq;
using Jellyfin.Data.Enums;
diff --git a/MediaBrowser.Controller/MediaEncoding/FilterOptionType.cs b/MediaBrowser.Controller/MediaEncoding/FilterOptionType.cs
index a2b6e1d73..6ad953023 100644
--- a/MediaBrowser.Controller/MediaEncoding/FilterOptionType.cs
+++ b/MediaBrowser.Controller/MediaEncoding/FilterOptionType.cs
@@ -38,6 +38,16 @@ namespace MediaBrowser.Controller.MediaEncoding
/// <summary>
/// The transpose_opencl_reversal.
/// </summary>
- TransposeOpenclReversal = 6
+ TransposeOpenclReversal = 6,
+
+ /// <summary>
+ /// The overlay_opencl_alpha_format.
+ /// </summary>
+ OverlayOpenclAlphaFormat = 7,
+
+ /// <summary>
+ /// The overlay_cuda_alpha_format.
+ /// </summary>
+ OverlayCudaAlphaFormat = 8
}
}
diff --git a/MediaBrowser.Controller/MediaEncoding/IAttachmentExtractor.cs b/MediaBrowser.Controller/MediaEncoding/IAttachmentExtractor.cs
index 09840d2ee..d8d136472 100644
--- a/MediaBrowser.Controller/MediaEncoding/IAttachmentExtractor.cs
+++ b/MediaBrowser.Controller/MediaEncoding/IAttachmentExtractor.cs
@@ -9,26 +9,33 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-namespace MediaBrowser.Controller.MediaEncoding
-{
- public interface IAttachmentExtractor
- {
- Task<(MediaAttachment Attachment, Stream Stream)> GetAttachment(
- BaseItem item,
- string mediaSourceId,
- int attachmentStreamIndex,
- CancellationToken cancellationToken);
+namespace MediaBrowser.Controller.MediaEncoding;
- Task ExtractAllAttachments(
- string inputFile,
- MediaSourceInfo mediaSource,
- string outputPath,
- CancellationToken cancellationToken);
+public interface IAttachmentExtractor
+{
+ /// <summary>
+ /// Gets the path to the attachment file.
+ /// </summary>
+ /// <param name="item">The <see cref="BaseItem"/>.</param>
+ /// <param name="mediaSourceId">The media source id.</param>
+ /// <param name="attachmentStreamIndex">The attachment index.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The async task.</returns>
+ Task<(MediaAttachment Attachment, Stream Stream)> GetAttachment(
+ BaseItem item,
+ string mediaSourceId,
+ int attachmentStreamIndex,
+ CancellationToken cancellationToken);
- Task ExtractAllAttachmentsExternal(
- string inputArgument,
- string id,
- string outputPath,
- CancellationToken cancellationToken);
- }
+ /// <summary>
+ /// Gets the path to the attachment file.
+ /// </summary>
+ /// <param name="inputFile">The input file path.</param>
+ /// <param name="mediaSource">The <see cref="MediaSourceInfo" /> source id.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The async task.</returns>
+ Task ExtractAllAttachments(
+ string inputFile,
+ MediaSourceInfo mediaSource,
+ CancellationToken cancellationToken);
}
diff --git a/MediaBrowser.Controller/MediaEncoding/IEncodingManager.cs b/MediaBrowser.Controller/MediaEncoding/IEncodingManager.cs
deleted file mode 100644
index 8ce40a58d..000000000
--- a/MediaBrowser.Controller/MediaEncoding/IEncodingManager.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-#nullable disable
-
-#pragma warning disable CS1591
-
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-
-namespace MediaBrowser.Controller.MediaEncoding
-{
- public interface IEncodingManager
- {
- /// <summary>
- /// Refreshes the chapter images.
- /// </summary>
- /// <param name="video">Video to use.</param>
- /// <param name="directoryService">Directory service to use.</param>
- /// <param name="chapters">Set of chapters to refresh.</param>
- /// <param name="extractImages">Option to extract images.</param>
- /// <param name="saveChapters">Option to save chapters.</param>
- /// <param name="cancellationToken">CancellationToken to use for operation.</param>
- /// <returns><c>true</c> if successful, <c>false</c> if not.</returns>
- Task<bool> RefreshChapterImages(Video video, IDirectoryService directoryService, IReadOnlyList<ChapterInfo> chapters, bool extractImages, bool saveChapters, CancellationToken cancellationToken);
- }
-}
diff --git a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs
index c767b4a51..de6353c4c 100644
--- a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs
+++ b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs
@@ -76,6 +76,12 @@ namespace MediaBrowser.Controller.MediaEncoding
bool IsVaapiDeviceSupportVulkanDrmInterop { get; }
/// <summary>
+ /// Gets a value indicating whether av1 decoding is available via VideoToolbox.
+ /// </summary>
+ /// <value><c>true</c> if the av1 is available via VideoToolbox, <c>false</c> otherwise.</value>
+ bool IsVideoToolboxAv1DecodeAvailable { get; }
+
+ /// <summary>
/// Whether given encoder codec is supported.
/// </summary>
/// <param name="encoder">The encoder.</param>
@@ -111,6 +117,13 @@ namespace MediaBrowser.Controller.MediaEncoding
bool SupportsFilterWithOption(FilterOptionType option);
/// <summary>
+ /// Whether the bitstream filter is supported with the given option.
+ /// </summary>
+ /// <param name="option">The option.</param>
+ /// <returns><c>true</c> if the bitstream filter is supported, <c>false</c> otherwise.</returns>
+ bool SupportsBitStreamFilterWithOption(BitStreamFilterOptionType option);
+
+ /// <summary>
/// Extracts the audio image.
/// </summary>
/// <param name="path">The path.</param>
diff --git a/MediaBrowser.Controller/MediaSegments/IMediaSegmentManager.cs b/MediaBrowser.Controller/MediaSegments/IMediaSegmentManager.cs
index 456977b88..720c607f1 100644
--- a/MediaBrowser.Controller/MediaSegments/IMediaSegmentManager.cs
+++ b/MediaBrowser.Controller/MediaSegments/IMediaSegmentManager.cs
@@ -5,9 +5,10 @@ using System.Threading.Tasks;
using Jellyfin.Database.Implementations.Entities;
using Jellyfin.Database.Implementations.Enums;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.MediaSegments;
-namespace MediaBrowser.Controller;
+namespace MediaBrowser.Controller.MediaSegments;
/// <summary>
/// Defines methods for interacting with media segments.
@@ -18,10 +19,11 @@ public interface IMediaSegmentManager
/// Uses all segment providers enabled for the <see cref="BaseItem"/>'s library to get the Media Segments.
/// </summary>
/// <param name="baseItem">The Item to evaluate.</param>
+ /// <param name="libraryOptions">The library options.</param>
/// <param name="overwrite">If set, will remove existing segments and replace it with new ones otherwise will check for existing segments and if found any, stops.</param>
- /// <param name="cancellationToken">stop request token.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A task that indicates the Operation is finished.</returns>
- Task RunSegmentPluginProviders(BaseItem baseItem, bool overwrite, CancellationToken cancellationToken);
+ Task RunSegmentPluginProviders(BaseItem baseItem, LibraryOptions libraryOptions, bool overwrite, CancellationToken cancellationToken);
/// <summary>
/// Returns if this item supports media segments.
@@ -46,22 +48,22 @@ public interface IMediaSegmentManager
Task DeleteSegmentAsync(Guid segmentId);
/// <summary>
- /// Obtains all segments associated with the itemId.
+ /// Deletes all media segments of an item.
/// </summary>
- /// <param name="itemId">The id of the <see cref="BaseItem"/>.</param>
- /// <param name="typeFilter">filters all media segments of the given type to be included. If null all types are included.</param>
- /// <param name="filterByProvider">When set filters the segments to only return those that which providers are currently enabled on their library.</param>
- /// <returns>An enumerator of <see cref="MediaSegmentDto"/>'s.</returns>
- Task<IEnumerable<MediaSegmentDto>> GetSegmentsAsync(Guid itemId, IEnumerable<MediaSegmentType>? typeFilter, bool filterByProvider = true);
+ /// <param name="itemId">The <see cref="BaseItem.Id"/> to delete all segments for.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>a task.</returns>
+ Task DeleteSegmentsAsync(Guid itemId, CancellationToken cancellationToken);
/// <summary>
/// Obtains all segments associated with the itemId.
/// </summary>
/// <param name="item">The <see cref="BaseItem"/>.</param>
/// <param name="typeFilter">filters all media segments of the given type to be included. If null all types are included.</param>
+ /// <param name="libraryOptions">The library options.</param>
/// <param name="filterByProvider">When set filters the segments to only return those that which providers are currently enabled on their library.</param>
/// <returns>An enumerator of <see cref="MediaSegmentDto"/>'s.</returns>
- Task<IEnumerable<MediaSegmentDto>> GetSegmentsAsync(BaseItem item, IEnumerable<MediaSegmentType>? typeFilter, bool filterByProvider = true);
+ Task<IEnumerable<MediaSegmentDto>> GetSegmentsAsync(BaseItem item, IEnumerable<MediaSegmentType>? typeFilter, LibraryOptions libraryOptions, bool filterByProvider = true);
/// <summary>
/// Gets information about any media segments stored for the given itemId.
diff --git a/MediaBrowser.Controller/MediaSegments/IMediaSegmentProvider.cs b/MediaBrowser.Controller/MediaSegments/IMediaSegmentProvider.cs
index 39bb58bef..5a6d15d78 100644
--- a/MediaBrowser.Controller/MediaSegments/IMediaSegmentProvider.cs
+++ b/MediaBrowser.Controller/MediaSegments/IMediaSegmentProvider.cs
@@ -1,13 +1,11 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
+using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model;
using MediaBrowser.Model.MediaSegments;
-namespace MediaBrowser.Controller;
+namespace MediaBrowser.Controller.MediaSegments;
/// <summary>
/// Provides methods for Obtaining the Media Segments from an Item.
diff --git a/MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandMessage.cs b/MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandMessage.cs
deleted file mode 100644
index 6a501aa7e..000000000
--- a/MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandMessage.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-using System.ComponentModel;
-using MediaBrowser.Model.Session;
-using MediaBrowser.Model.SyncPlay;
-
-namespace MediaBrowser.Controller.Net.WebSocketMessages.Outbound;
-
-/// <summary>
-/// Untyped sync play command.
-/// </summary>
-public class SyncPlayGroupUpdateCommandMessage : OutboundWebSocketMessage<GroupUpdate>
-{
- /// <summary>
- /// Initializes a new instance of the <see cref="SyncPlayGroupUpdateCommandMessage"/> class.
- /// </summary>
- /// <param name="data">The send command.</param>
- public SyncPlayGroupUpdateCommandMessage(GroupUpdate data)
- : base(data)
- {
- }
-
- /// <inheritdoc />
- [DefaultValue(SessionMessageType.SyncPlayGroupUpdate)]
- public override SessionMessageType MessageType => SessionMessageType.SyncPlayGroupUpdate;
-}
diff --git a/MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfGroupInfoMessage.cs b/MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfGroupInfoMessage.cs
deleted file mode 100644
index 47f706e2a..000000000
--- a/MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfGroupInfoMessage.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-using System.ComponentModel;
-using MediaBrowser.Model.Session;
-using MediaBrowser.Model.SyncPlay;
-
-namespace MediaBrowser.Controller.Net.WebSocketMessages.Outbound;
-
-/// <summary>
-/// Sync play group update command with group info.
-/// GroupUpdateTypes: GroupJoined.
-/// </summary>
-public class SyncPlayGroupUpdateCommandOfGroupInfoMessage : OutboundWebSocketMessage<GroupUpdate<GroupInfoDto>>
-{
- /// <summary>
- /// Initializes a new instance of the <see cref="SyncPlayGroupUpdateCommandOfGroupInfoMessage"/> class.
- /// </summary>
- /// <param name="data">The group info.</param>
- public SyncPlayGroupUpdateCommandOfGroupInfoMessage(GroupUpdate<GroupInfoDto> data)
- : base(data)
- {
- }
-
- /// <inheritdoc />
- [DefaultValue(SessionMessageType.SyncPlayGroupUpdate)]
- public override SessionMessageType MessageType => SessionMessageType.SyncPlayGroupUpdate;
-}
diff --git a/MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfGroupStateUpdateMessage.cs b/MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfGroupStateUpdateMessage.cs
deleted file mode 100644
index 11ddb1e25..000000000
--- a/MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfGroupStateUpdateMessage.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-using System.ComponentModel;
-using MediaBrowser.Model.Session;
-using MediaBrowser.Model.SyncPlay;
-
-namespace MediaBrowser.Controller.Net.WebSocketMessages.Outbound;
-
-/// <summary>
-/// Sync play group update command with group state update.
-/// GroupUpdateTypes: StateUpdate.
-/// </summary>
-public class SyncPlayGroupUpdateCommandOfGroupStateUpdateMessage : OutboundWebSocketMessage<GroupUpdate<GroupStateUpdate>>
-{
- /// <summary>
- /// Initializes a new instance of the <see cref="SyncPlayGroupUpdateCommandOfGroupStateUpdateMessage"/> class.
- /// </summary>
- /// <param name="data">The group info.</param>
- public SyncPlayGroupUpdateCommandOfGroupStateUpdateMessage(GroupUpdate<GroupStateUpdate> data)
- : base(data)
- {
- }
-
- /// <inheritdoc />
- [DefaultValue(SessionMessageType.SyncPlayGroupUpdate)]
- public override SessionMessageType MessageType => SessionMessageType.SyncPlayGroupUpdate;
-}
diff --git a/MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfPlayQueueUpdateMessage.cs b/MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfPlayQueueUpdateMessage.cs
deleted file mode 100644
index 7e73399b1..000000000
--- a/MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfPlayQueueUpdateMessage.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-using System.ComponentModel;
-using MediaBrowser.Model.Session;
-using MediaBrowser.Model.SyncPlay;
-
-namespace MediaBrowser.Controller.Net.WebSocketMessages.Outbound;
-
-/// <summary>
-/// Sync play group update command with play queue update.
-/// GroupUpdateTypes: PlayQueue.
-/// </summary>
-public class SyncPlayGroupUpdateCommandOfPlayQueueUpdateMessage : OutboundWebSocketMessage<GroupUpdate<PlayQueueUpdate>>
-{
- /// <summary>
- /// Initializes a new instance of the <see cref="SyncPlayGroupUpdateCommandOfPlayQueueUpdateMessage"/> class.
- /// </summary>
- /// <param name="data">The play queue update.</param>
- public SyncPlayGroupUpdateCommandOfPlayQueueUpdateMessage(GroupUpdate<PlayQueueUpdate> data)
- : base(data)
- {
- }
-
- /// <inheritdoc />
- [DefaultValue(SessionMessageType.SyncPlayGroupUpdate)]
- public override SessionMessageType MessageType => SessionMessageType.SyncPlayGroupUpdate;
-}
diff --git a/MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfStringMessage.cs b/MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfStringMessage.cs
deleted file mode 100644
index 5b5ccd3ed..000000000
--- a/MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfStringMessage.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-using System.ComponentModel;
-using MediaBrowser.Model.Session;
-using MediaBrowser.Model.SyncPlay;
-
-namespace MediaBrowser.Controller.Net.WebSocketMessages.Outbound;
-
-/// <summary>
-/// Sync play group update command with string.
-/// GroupUpdateTypes: GroupDoesNotExist (error), LibraryAccessDenied (error), NotInGroup (error), GroupLeft (groupId), UserJoined (username), UserLeft (username).
-/// </summary>
-public class SyncPlayGroupUpdateCommandOfStringMessage : OutboundWebSocketMessage<GroupUpdate<string>>
-{
- /// <summary>
- /// Initializes a new instance of the <see cref="SyncPlayGroupUpdateCommandOfStringMessage"/> class.
- /// </summary>
- /// <param name="data">The send command.</param>
- public SyncPlayGroupUpdateCommandOfStringMessage(GroupUpdate<string> data)
- : base(data)
- {
- }
-
- /// <inheritdoc />
- [DefaultValue(SessionMessageType.SyncPlayGroupUpdate)]
- public override SessionMessageType MessageType => SessionMessageType.SyncPlayGroupUpdate;
-}
diff --git a/MediaBrowser.Controller/Chapters/IChapterRepository.cs b/MediaBrowser.Controller/Persistence/IChapterRepository.cs
index e22cb0f58..0844ddb36 100644
--- a/MediaBrowser.Controller/Chapters/IChapterRepository.cs
+++ b/MediaBrowser.Controller/Persistence/IChapterRepository.cs
@@ -1,36 +1,26 @@
using System;
using System.Collections.Generic;
-using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-namespace MediaBrowser.Controller.Chapters;
+namespace MediaBrowser.Controller.Persistence;
/// <summary>
-/// Interface IChapterManager.
+/// Interface IChapterRepository.
/// </summary>
public interface IChapterRepository
{
/// <summary>
- /// Saves the chapters.
+ /// Deletes the chapters.
/// </summary>
/// <param name="itemId">The item.</param>
- /// <param name="chapters">The set of chapters.</param>
- void SaveChapters(Guid itemId, IReadOnlyList<ChapterInfo> chapters);
-
- /// <summary>
- /// Gets all chapters associated with the baseItem.
- /// </summary>
- /// <param name="baseItem">The baseitem.</param>
- /// <returns>A readonly list of chapter instances.</returns>
- IReadOnlyList<ChapterInfo> GetChapters(BaseItemDto baseItem);
+ void DeleteChapters(Guid itemId);
/// <summary>
- /// Gets a single chapter of a BaseItem on a specific index.
+ /// Saves the chapters.
/// </summary>
- /// <param name="baseItem">The baseitem.</param>
- /// <param name="index">The index of that chapter.</param>
- /// <returns>A chapter instance.</returns>
- ChapterInfo? GetChapter(BaseItemDto baseItem, int index);
+ /// <param name="itemId">The item.</param>
+ /// <param name="chapters">The set of chapters.</param>
+ void SaveChapters(Guid itemId, IReadOnlyList<ChapterInfo> chapters);
/// <summary>
/// Gets all chapters associated with the baseItem.
diff --git a/MediaBrowser.Controller/Persistence/IKeyframeRepository.cs b/MediaBrowser.Controller/Persistence/IKeyframeRepository.cs
new file mode 100644
index 000000000..2596784ba
--- /dev/null
+++ b/MediaBrowser.Controller/Persistence/IKeyframeRepository.cs
@@ -0,0 +1,37 @@
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.MediaEncoding.Keyframes;
+
+namespace MediaBrowser.Controller.Persistence;
+
+/// <summary>
+/// Provides methods for accessing keyframe data.
+/// </summary>
+public interface IKeyframeRepository
+{
+ /// <summary>
+ /// Gets the keyframe data.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <returns>The keyframe data.</returns>
+ IReadOnlyList<KeyframeData> GetKeyframeData(Guid itemId);
+
+ /// <summary>
+ /// Saves the keyframe data.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="data">The keyframe data.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The task object representing the asynchronous operation.</returns>
+ Task SaveKeyframeDataAsync(Guid itemId, KeyframeData data, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Deletes the keyframe data.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The task object representing the asynchronous operation.</returns>
+ Task DeleteKeyframeDataAsync(Guid itemId, CancellationToken cancellationToken);
+}
diff --git a/MediaBrowser.Controller/Session/ISessionManager.cs b/MediaBrowser.Controller/Session/ISessionManager.cs
index 47bcfdb6e..2b3afa117 100644
--- a/MediaBrowser.Controller/Session/ISessionManager.cs
+++ b/MediaBrowser.Controller/Session/ISessionManager.cs
@@ -161,7 +161,7 @@ namespace MediaBrowser.Controller.Session
/// <param name="sessionId">The identifier of the session.</param>
/// <param name="command">The group update.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <typeparam name="T">Type of group.</typeparam>
+ /// <typeparam name="T">The group update type.</typeparam>
/// <returns>Task.</returns>
Task SendSyncPlayGroupUpdate<T>(string sessionId, GroupUpdate<T> command, CancellationToken cancellationToken);
diff --git a/MediaBrowser.Controller/Sorting/IUserBaseItemComparer.cs b/MediaBrowser.Controller/Sorting/IUserBaseItemComparer.cs
index 97f653edf..2206a021a 100644
--- a/MediaBrowser.Controller/Sorting/IUserBaseItemComparer.cs
+++ b/MediaBrowser.Controller/Sorting/IUserBaseItemComparer.cs
@@ -26,6 +26,6 @@ namespace MediaBrowser.Controller.Sorting
/// Gets or sets the user data repository.
/// </summary>
/// <value>The user data repository.</value>
- IUserDataManager UserDataRepository { get; set; }
+ IUserDataManager UserDataManager { get; set; }
}
}
diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs
index 51c95a1bb..31890c40a 100644
--- a/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs
+++ b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs
@@ -80,7 +80,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates
}
var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.RemoveItems);
- var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ var update = new SyncPlayPlayQueueUpdate(context.GroupId, playQueueUpdate);
context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
if (playingItemRemoved && !context.PlayQueue.IsItemPlaying())
@@ -106,7 +106,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates
}
var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.MoveItem);
- var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ var update = new SyncPlayPlayQueueUpdate(context.GroupId, playQueueUpdate);
context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
}
@@ -127,7 +127,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates
_ => PlayQueueUpdateReason.Queue
};
var playQueueUpdate = context.GetPlayQueueUpdate(reason);
- var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ var update = new SyncPlayPlayQueueUpdate(context.GroupId, playQueueUpdate);
context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
}
@@ -184,7 +184,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates
{
context.SetRepeatMode(request.Mode);
var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.RepeatMode);
- var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ var update = new SyncPlayPlayQueueUpdate(context.GroupId, playQueueUpdate);
context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
}
@@ -193,7 +193,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates
{
context.SetShuffleMode(request.Mode);
var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.ShuffleMode);
- var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ var update = new SyncPlayPlayQueueUpdate(context.GroupId, playQueueUpdate);
context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
}
@@ -221,7 +221,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates
{
// Notify relevant state change event.
var stateUpdate = new GroupStateUpdate(Type, reason.Action);
- var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.StateUpdate, stateUpdate);
+ var update = new SyncPlayStateUpdate(context.GroupId, stateUpdate);
context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
}
diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs
index dcc06db1e..132765b71 100644
--- a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs
+++ b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs
@@ -78,7 +78,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates
// Prepare new session.
var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NewPlaylist);
- var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ var update = new SyncPlayPlayQueueUpdate(context.GroupId, playQueueUpdate);
context.SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, update, cancellationToken);
context.SetBuffering(session, true);
@@ -152,7 +152,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates
}
var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NewPlaylist);
- var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ var update = new SyncPlayPlayQueueUpdate(context.GroupId, playQueueUpdate);
context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
// Reset status of sessions and await for all Ready events.
@@ -177,7 +177,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates
if (result)
{
var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.SetCurrentItem);
- var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ var update = new SyncPlayPlayQueueUpdate(context.GroupId, playQueueUpdate);
context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
// Reset status of sessions and await for all Ready events.
@@ -215,7 +215,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates
context.RestartCurrentItem();
var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NewPlaylist);
- var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ var update = new SyncPlayPlayQueueUpdate(context.GroupId, playQueueUpdate);
context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
// Reset status of sessions and await for all Ready events.
@@ -336,7 +336,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates
_logger.LogDebug("Session {SessionId} reported wrong playlist item in group {GroupId}.", session.Id, context.GroupId.ToString());
var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.SetCurrentItem);
- var updateSession = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ var updateSession = new SyncPlayPlayQueueUpdate(context.GroupId, playQueueUpdate);
context.SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken);
context.SetBuffering(session, true);
@@ -410,7 +410,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates
_logger.LogDebug("Session {SessionId} reported wrong playlist item in group {GroupId}.", session.Id, context.GroupId.ToString());
var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.SetCurrentItem);
- var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ var update = new SyncPlayPlayQueueUpdate(context.GroupId, playQueueUpdate);
context.SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, update, cancellationToken);
context.SetBuffering(session, true);
@@ -583,7 +583,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates
{
// Send playing-queue update.
var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NextItem);
- var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ var update = new SyncPlayPlayQueueUpdate(context.GroupId, playQueueUpdate);
context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
// Reset status of sessions and await for all Ready events.
@@ -629,7 +629,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates
{
// Send playing-queue update.
var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.PreviousItem);
- var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate);
+ var update = new SyncPlayPlayQueueUpdate(context.GroupId, playQueueUpdate);
context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken);
// Reset status of sessions and await for all Ready events.
diff --git a/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs b/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs
index d2de22450..ddf86be71 100644
--- a/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs
+++ b/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs
@@ -66,11 +66,11 @@ namespace MediaBrowser.Controller.SyncPlay
/// <summary>
/// Sends a GroupUpdate message to the interested sessions.
/// </summary>
- /// <typeparam name="T">The type of the data of the message.</typeparam>
/// <param name="from">The current session.</param>
/// <param name="type">The filtering type.</param>
/// <param name="message">The message to send.</param>
/// <param name="cancellationToken">The cancellation token.</param>
+ /// <typeparam name="T">The group update type.</typeparam>
/// <returns>The task.</returns>
Task SendGroupUpdate<T>(SessionInfo from, SyncPlayBroadcastType type, GroupUpdate<T> message, CancellationToken cancellationToken);
@@ -92,15 +92,6 @@ namespace MediaBrowser.Controller.SyncPlay
SendCommand NewSyncPlayCommand(SendCommandType type);
/// <summary>
- /// Builds a new group update message.
- /// </summary>
- /// <typeparam name="T">The type of the data of the message.</typeparam>
- /// <param name="type">The update type.</param>
- /// <param name="data">The data to send.</param>
- /// <returns>The group update.</returns>
- GroupUpdate<T> NewSyncPlayGroupUpdate<T>(GroupUpdateType type, T data);
-
- /// <summary>
/// Sanitizes the PositionTicks, considers the current playing item when available.
/// </summary>
/// <param name="positionTicks">The PositionTicks.</param>
diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs
index a6999a12c..6365a389e 100644
--- a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs
+++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs
@@ -20,7 +20,8 @@ namespace MediaBrowser.Controller.SyncPlay
/// <param name="session">The session that's creating the group.</param>
/// <param name="request">The request.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- void NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken);
+ /// <returns>The newly created group.</returns>
+ GroupInfoDto NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken);
/// <summary>
/// Adds the session to a group.
@@ -47,6 +48,14 @@ namespace MediaBrowser.Controller.SyncPlay
List<GroupInfoDto> ListGroups(SessionInfo session, ListGroupsRequest request);
/// <summary>
+ /// Gets available groups for a session by id.
+ /// </summary>
+ /// <param name="session">The session.</param>
+ /// <param name="groupId">The group id.</param>
+ /// <returns>The groups or null.</returns>
+ GroupInfoDto GetGroup(SessionInfo session, Guid groupId);
+
+ /// <summary>
/// Handle a request by a session in a group.
/// </summary>
/// <param name="session">The session.</param>
diff --git a/MediaBrowser.Controller/SystemBackupService/BackupManifestDto.cs b/MediaBrowser.Controller/SystemBackupService/BackupManifestDto.cs
new file mode 100644
index 000000000..b094ec275
--- /dev/null
+++ b/MediaBrowser.Controller/SystemBackupService/BackupManifestDto.cs
@@ -0,0 +1,34 @@
+using System;
+
+namespace MediaBrowser.Controller.SystemBackupService;
+
+/// <summary>
+/// Manifest type for backups internal structure.
+/// </summary>
+public class BackupManifestDto
+{
+ /// <summary>
+ /// Gets or sets the jellyfin version this backup was created with.
+ /// </summary>
+ public required Version ServerVersion { get; set; }
+
+ /// <summary>
+ /// Gets or sets the backup engine version this backup was created with.
+ /// </summary>
+ public required Version BackupEngineVersion { get; set; }
+
+ /// <summary>
+ /// Gets or sets the date this backup was created with.
+ /// </summary>
+ public required DateTimeOffset DateCreated { get; set; }
+
+ /// <summary>
+ /// Gets or sets the path to the backup on the system.
+ /// </summary>
+ public required string Path { get; set; }
+
+ /// <summary>
+ /// Gets or sets the contents of the backup archive.
+ /// </summary>
+ public required BackupOptionsDto Options { get; set; }
+}
diff --git a/MediaBrowser.Controller/SystemBackupService/BackupOptionsDto.cs b/MediaBrowser.Controller/SystemBackupService/BackupOptionsDto.cs
new file mode 100644
index 000000000..fc5a109f1
--- /dev/null
+++ b/MediaBrowser.Controller/SystemBackupService/BackupOptionsDto.cs
@@ -0,0 +1,29 @@
+using System;
+
+namespace MediaBrowser.Controller.SystemBackupService;
+
+/// <summary>
+/// Defines the optional contents of the backup archive.
+/// </summary>
+public class BackupOptionsDto
+{
+ /// <summary>
+ /// Gets or sets a value indicating whether the archive contains the Metadata contents.
+ /// </summary>
+ public bool Metadata { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the archive contains the Trickplay contents.
+ /// </summary>
+ public bool Trickplay { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the archive contains the Subtitle contents.
+ /// </summary>
+ public bool Subtitles { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the archive contains the Database contents.
+ /// </summary>
+ public bool Database { get; set; } = true;
+}
diff --git a/MediaBrowser.Controller/SystemBackupService/BackupRestoreRequestDto.cs b/MediaBrowser.Controller/SystemBackupService/BackupRestoreRequestDto.cs
new file mode 100644
index 000000000..263fa00c8
--- /dev/null
+++ b/MediaBrowser.Controller/SystemBackupService/BackupRestoreRequestDto.cs
@@ -0,0 +1,15 @@
+using System;
+using MediaBrowser.Common.Configuration;
+
+namespace MediaBrowser.Controller.SystemBackupService;
+
+/// <summary>
+/// Defines properties used to start a restore process.
+/// </summary>
+public class BackupRestoreRequestDto
+{
+ /// <summary>
+ /// Gets or Sets the name of the backup archive to restore from. Must be present in <see cref="IApplicationPaths.BackupPath"/>.
+ /// </summary>
+ public required string ArchiveFileName { get; set; }
+}
diff --git a/MediaBrowser.Controller/SystemBackupService/IBackupService.cs b/MediaBrowser.Controller/SystemBackupService/IBackupService.cs
new file mode 100644
index 000000000..0c586d811
--- /dev/null
+++ b/MediaBrowser.Controller/SystemBackupService/IBackupService.cs
@@ -0,0 +1,48 @@
+using System;
+using System.IO;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.SystemBackupService;
+
+namespace Jellyfin.Server.Implementations.SystemBackupService;
+
+/// <summary>
+/// Defines an interface to restore and backup the jellyfin system.
+/// </summary>
+public interface IBackupService
+{
+ /// <summary>
+ /// Creates a new Backup zip file containing the current state of the application.
+ /// </summary>
+ /// <param name="backupOptions">The backup options.</param>
+ /// <returns>A task.</returns>
+ Task<BackupManifestDto> CreateBackupAsync(BackupOptionsDto backupOptions);
+
+ /// <summary>
+ /// Gets a list of backups that are available to be restored from.
+ /// </summary>
+ /// <returns>A list of backup paths.</returns>
+ Task<BackupManifestDto[]> EnumerateBackups();
+
+ /// <summary>
+ /// Gets a single backup manifest if the path defines a valid Jellyfin backup archive.
+ /// </summary>
+ /// <param name="archivePath">The path to be loaded.</param>
+ /// <returns>The containing backup manifest or null if not existing or compatiable.</returns>
+ Task<BackupManifestDto?> GetBackupManifest(string archivePath);
+
+ /// <summary>
+ /// Restores an backup zip file created by jellyfin.
+ /// </summary>
+ /// <param name="archivePath">Path to the archive.</param>
+ /// <returns>A Task.</returns>
+ /// <exception cref="FileNotFoundException">Thrown when an invalid or missing file is specified.</exception>
+ /// <exception cref="NotSupportedException">Thrown when attempt to load an unsupported backup is made.</exception>
+ /// <exception cref="InvalidOperationException">Thrown for errors during the restore.</exception>
+ Task RestoreBackupAsync(string archivePath);
+
+ /// <summary>
+ /// Schedules a Restore and restarts the server.
+ /// </summary>
+ /// <param name="archivePath">The path to the archive to restore from.</param>
+ void ScheduleRestoreAndRestartServer(string archivePath);
+}
diff --git a/MediaBrowser.Controller/Trickplay/ITrickplayManager.cs b/MediaBrowser.Controller/Trickplay/ITrickplayManager.cs
index 9ac8ead11..fba24329a 100644
--- a/MediaBrowser.Controller/Trickplay/ITrickplayManager.cs
+++ b/MediaBrowser.Controller/Trickplay/ITrickplayManager.cs
@@ -21,7 +21,7 @@ public interface ITrickplayManager
/// <param name="libraryOptions">The library options.</param>
/// <param name="cancellationToken">CancellationToken to use for operation.</param>
/// <returns>Task.</returns>
- Task RefreshTrickplayDataAsync(Video video, bool replace, LibraryOptions? libraryOptions, CancellationToken cancellationToken);
+ Task RefreshTrickplayDataAsync(Video video, bool replace, LibraryOptions libraryOptions, CancellationToken cancellationToken);
/// <summary>
/// Creates trickplay tiles out of individual thumbnails.
@@ -59,6 +59,14 @@ public interface ITrickplayManager
Task SaveTrickplayInfo(TrickplayInfo info);
/// <summary>
+ /// Deletes all trickplay info for an item.
+ /// </summary>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Task.</returns>
+ Task DeleteTrickplayDataAsync(Guid itemId, CancellationToken cancellationToken);
+
+ /// <summary>
/// Gets all trickplay infos for all media streams of an item.
/// </summary>
/// <param name="item">The item.</param>
@@ -93,7 +101,7 @@ public interface ITrickplayManager
/// <param name="libraryOptions">The library options.</param>
/// <param name="cancellationToken">CancellationToken to use for operation.</param>
/// <returns>Task.</returns>
- Task MoveGeneratedTrickplayDataAsync(Video video, LibraryOptions? libraryOptions, CancellationToken cancellationToken);
+ Task MoveGeneratedTrickplayDataAsync(Video video, LibraryOptions libraryOptions, CancellationToken cancellationToken);
/// <summary>
/// Gets the trickplay HLS playlist.
diff --git a/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs b/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs
index 0bb341da1..f56bc71d0 100644
--- a/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs
+++ b/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs
@@ -33,7 +33,8 @@ namespace MediaBrowser.LocalMetadata.Images
"poster",
"cover",
"jacket",
- "default"
+ "default",
+ "albumart"
};
private static readonly string[] _personImageFileNames =
diff --git a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs
index 431fc0b17..48a0654bb 100644
--- a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs
+++ b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs
@@ -1,7 +1,4 @@
-#pragma warning disable CS1591
-
using System;
-using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
@@ -9,28 +6,27 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AsyncKeyedLock;
-using MediaBrowser.Common;
-using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.MediaEncoding.Encoder;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.MediaInfo;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.MediaEncoding.Attachments
{
+ /// <inheritdoc cref="IAttachmentExtractor"/>
public sealed class AttachmentExtractor : IAttachmentExtractor, IDisposable
{
private readonly ILogger<AttachmentExtractor> _logger;
- private readonly IApplicationPaths _appPaths;
private readonly IFileSystem _fileSystem;
private readonly IMediaEncoder _mediaEncoder;
private readonly IMediaSourceManager _mediaSourceManager;
+ private readonly IPathManager _pathManager;
private readonly AsyncKeyedLocker<string> _semaphoreLocks = new(o =>
{
@@ -38,18 +34,26 @@ namespace MediaBrowser.MediaEncoding.Attachments
o.PoolInitialFill = 1;
});
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AttachmentExtractor"/> class.
+ /// </summary>
+ /// <param name="logger">The <see cref="ILogger{AttachmentExtractor}"/>.</param>
+ /// <param name="fileSystem">The <see cref="IFileSystem"/>.</param>
+ /// <param name="mediaEncoder">The <see cref="IMediaEncoder"/>.</param>
+ /// <param name="mediaSourceManager">The <see cref="IMediaSourceManager"/>.</param>
+ /// <param name="pathManager">The <see cref="IPathManager"/>.</param>
public AttachmentExtractor(
ILogger<AttachmentExtractor> logger,
- IApplicationPaths appPaths,
IFileSystem fileSystem,
IMediaEncoder mediaEncoder,
- IMediaSourceManager mediaSourceManager)
+ IMediaSourceManager mediaSourceManager,
+ IPathManager pathManager)
{
_logger = logger;
- _appPaths = appPaths;
_fileSystem = fileSystem;
_mediaEncoder = mediaEncoder;
_mediaSourceManager = mediaSourceManager;
+ _pathManager = pathManager;
}
/// <inheritdoc />
@@ -77,350 +81,177 @@ namespace MediaBrowser.MediaEncoding.Attachments
throw new ResourceNotFoundException($"MediaSource {mediaSourceId} has no attachment with stream index {attachmentStreamIndex}");
}
+ if (string.Equals(mediaAttachment.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
+ {
+ throw new ResourceNotFoundException($"Attachment with stream index {attachmentStreamIndex} can't be extracted for MediaSource {mediaSourceId}");
+ }
+
var attachmentStream = await GetAttachmentStream(mediaSource, mediaAttachment, cancellationToken)
.ConfigureAwait(false);
return (mediaAttachment, attachmentStream);
}
+ /// <inheritdoc />
public async Task ExtractAllAttachments(
string inputFile,
MediaSourceInfo mediaSource,
- string outputPath,
CancellationToken cancellationToken)
{
var shouldExtractOneByOne = mediaSource.MediaAttachments.Any(a => !string.IsNullOrEmpty(a.FileName)
&& (a.FileName.Contains('/', StringComparison.OrdinalIgnoreCase) || a.FileName.Contains('\\', StringComparison.OrdinalIgnoreCase)));
- if (shouldExtractOneByOne)
- {
- var attachmentIndexes = mediaSource.MediaAttachments.Select(a => a.Index);
- foreach (var i in attachmentIndexes)
- {
- var newName = Path.Join(outputPath, i.ToString(CultureInfo.InvariantCulture));
- await ExtractAttachment(inputFile, mediaSource, i, newName, cancellationToken).ConfigureAwait(false);
- }
- }
- else
+ if (shouldExtractOneByOne && !inputFile.EndsWith(".mks", StringComparison.OrdinalIgnoreCase))
{
- using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
+ foreach (var attachment in mediaSource.MediaAttachments)
{
- if (!Directory.Exists(outputPath))
+ if (!string.Equals(attachment.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
{
- await ExtractAllAttachmentsInternal(
- _mediaEncoder.GetInputArgument(inputFile, mediaSource),
- outputPath,
- false,
- cancellationToken).ConfigureAwait(false);
+ await ExtractAttachment(inputFile, mediaSource, attachment, cancellationToken).ConfigureAwait(false);
}
}
}
- }
-
- public async Task ExtractAllAttachmentsExternal(
- string inputArgument,
- string id,
- string outputPath,
- CancellationToken cancellationToken)
- {
- using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
+ else
{
- if (!File.Exists(Path.Join(outputPath, id)))
- {
- await ExtractAllAttachmentsInternal(
- inputArgument,
- outputPath,
- true,
- cancellationToken).ConfigureAwait(false);
-
- if (Directory.Exists(outputPath))
- {
- File.Create(Path.Join(outputPath, id));
- }
- }
+ await ExtractAllAttachmentsInternal(
+ inputFile,
+ mediaSource,
+ false,
+ cancellationToken).ConfigureAwait(false);
}
}
private async Task ExtractAllAttachmentsInternal(
- string inputPath,
- string outputPath,
+ string inputFile,
+ MediaSourceInfo mediaSource,
bool isExternal,
CancellationToken cancellationToken)
{
- ArgumentException.ThrowIfNullOrEmpty(inputPath);
- ArgumentException.ThrowIfNullOrEmpty(outputPath);
-
- Directory.CreateDirectory(outputPath);
-
- var processArgs = string.Format(
- CultureInfo.InvariantCulture,
- "-dump_attachment:t \"\" -y {0} -i {1} -t 0 -f null null",
- inputPath.EndsWith(".concat\"", StringComparison.OrdinalIgnoreCase) ? "-f concat -safe 0" : string.Empty,
- inputPath);
+ var inputPath = _mediaEncoder.GetInputArgument(inputFile, mediaSource);
- int exitCode;
+ ArgumentException.ThrowIfNullOrEmpty(inputPath);
- using (var process = new Process
- {
- StartInfo = new ProcessStartInfo
- {
- Arguments = processArgs,
- FileName = _mediaEncoder.EncoderPath,
- UseShellExecute = false,
- CreateNoWindow = true,
- WindowStyle = ProcessWindowStyle.Hidden,
- WorkingDirectory = outputPath,
- ErrorDialog = false
- },
- EnableRaisingEvents = true
- })
+ var outputFolder = _pathManager.GetAttachmentFolderPath(mediaSource.Id);
+ using (await _semaphoreLocks.LockAsync(outputFolder, cancellationToken).ConfigureAwait(false))
{
- _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
-
- process.Start();
-
- try
+ 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())
{
- await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
- exitCode = process.ExitCode;
- }
- catch (OperationCanceledException)
- {
- process.Kill(true);
- exitCode = -1;
+ // Skip extraction if all files already exist
+ return;
}
- }
- var failed = false;
+ var processArgs = string.Format(
+ CultureInfo.InvariantCulture,
+ "-dump_attachment:t \"\" -y {0} -i {1} -t 0 -f null null",
+ inputPath.EndsWith(".concat\"", StringComparison.OrdinalIgnoreCase) ? "-f concat -safe 0" : string.Empty,
+ inputPath);
- if (exitCode != 0)
- {
- if (isExternal && exitCode == 1)
- {
- // ffmpeg returns exitCode 1 because there is no video or audio stream
- // this can be ignored
- }
- else
+ 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
+ })
{
- failed = true;
+ _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
+
+ process.Start();
- _logger.LogWarning("Deleting extracted attachments {Path} due to failure: {ExitCode}", outputPath, exitCode);
try
{
- Directory.Delete(outputPath);
+ await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
+ exitCode = process.ExitCode;
}
- catch (IOException ex)
+ catch (OperationCanceledException)
{
- _logger.LogError(ex, "Error deleting extracted attachments {Path}", outputPath);
+ process.Kill(true);
+ exitCode = -1;
}
}
- }
- else if (!Directory.Exists(outputPath))
- {
- failed = true;
- }
-
- if (failed)
- {
- _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
- throw new InvalidOperationException(
- string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
- }
-
- _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
- }
-
- private async Task<Stream> GetAttachmentStream(
- MediaSourceInfo mediaSource,
- MediaAttachment mediaAttachment,
- CancellationToken cancellationToken)
- {
- var attachmentPath = await GetReadableFile(mediaSource.Path, mediaSource.Path, mediaSource, mediaAttachment, cancellationToken).ConfigureAwait(false);
- return AsyncFile.OpenRead(attachmentPath);
- }
-
- private async Task<string> GetReadableFile(
- string mediaPath,
- string inputFile,
- MediaSourceInfo mediaSource,
- MediaAttachment mediaAttachment,
- CancellationToken cancellationToken)
- {
- await CacheAllAttachments(mediaPath, inputFile, mediaSource, cancellationToken).ConfigureAwait(false);
-
- var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, mediaAttachment.Index);
- await ExtractAttachment(inputFile, mediaSource, mediaAttachment.Index, outputPath, cancellationToken)
- .ConfigureAwait(false);
-
- return outputPath;
- }
-
- private async Task CacheAllAttachments(
- string mediaPath,
- string inputFile,
- MediaSourceInfo mediaSource,
- CancellationToken cancellationToken)
- {
- var outputFileLocks = new List<IDisposable>();
- var extractableAttachmentIds = new List<int>();
+ var failed = false;
- try
- {
- foreach (var attachment in mediaSource.MediaAttachments)
+ if (exitCode != 0)
{
- var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, attachment.Index);
-
- var releaser = await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false);
-
- if (File.Exists(outputPath))
+ if (isExternal && exitCode == 1)
{
- releaser.Dispose();
- continue;
+ // ffmpeg returns exitCode 1 because there is no video or audio stream
+ // this can be ignored
}
-
- outputFileLocks.Add(releaser);
- extractableAttachmentIds.Add(attachment.Index);
- }
-
- if (extractableAttachmentIds.Count > 0)
- {
- await CacheAllAttachmentsInternal(mediaPath, _mediaEncoder.GetInputArgument(inputFile, mediaSource), mediaSource, extractableAttachmentIds, cancellationToken).ConfigureAwait(false);
- }
- }
- catch (Exception ex)
- {
- _logger.LogWarning(ex, "Unable to cache media attachments for File:{File}", mediaPath);
- }
- finally
- {
- outputFileLocks.ForEach(x => x.Dispose());
- }
- }
-
- private async Task CacheAllAttachmentsInternal(
- string mediaPath,
- string inputFile,
- MediaSourceInfo mediaSource,
- List<int> extractableAttachmentIds,
- CancellationToken cancellationToken)
- {
- var outputPaths = new List<string>();
- var processArgs = string.Empty;
-
- foreach (var attachmentId in extractableAttachmentIds)
- {
- var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, attachmentId);
-
- Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calculated path ({outputPath}) is not valid."));
-
- outputPaths.Add(outputPath);
- processArgs += string.Format(
- CultureInfo.InvariantCulture,
- " -dump_attachment:{0} \"{1}\"",
- attachmentId,
- EncodingUtils.NormalizePath(outputPath));
- }
-
- processArgs += string.Format(
- CultureInfo.InvariantCulture,
- " -i {0} -t 0 -f null null",
- inputFile);
-
- int exitCode;
-
- using (var process = new Process
- {
- StartInfo = new ProcessStartInfo
+ else
{
- Arguments = processArgs,
- FileName = _mediaEncoder.EncoderPath,
- UseShellExecute = false,
- CreateNoWindow = true,
- WindowStyle = ProcessWindowStyle.Hidden,
- ErrorDialog = false
- },
- EnableRaisingEvents = true
- })
- {
- _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
-
- process.Start();
+ failed = true;
- try
- {
- await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
- exitCode = process.ExitCode;
+ _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);
+ }
+ }
}
- catch (OperationCanceledException)
+ else if (!Directory.Exists(outputFolder))
{
- process.Kill(true);
- exitCode = -1;
+ failed = true;
}
- }
- var failed = false;
-
- if (exitCode == -1)
- {
- failed = true;
-
- foreach (var outputPath in outputPaths)
+ if (failed)
{
- try
- {
- _logger.LogWarning("Deleting extracted media attachment due to failure: {Path}", outputPath);
- _fileSystem.DeleteFile(outputPath);
- }
- catch (FileNotFoundException)
- {
- // ffmpeg failed, so it is normal that one or more expected output files do not exist.
- // There is no need to log anything for the user here.
- }
- catch (IOException ex)
- {
- _logger.LogError(ex, "Error deleting extracted media attachment {Path}", outputPath);
- }
- }
- }
- else
- {
- foreach (var outputPath in outputPaths)
- {
- if (!File.Exists(outputPath))
- {
- _logger.LogError("ffmpeg media attachment extraction failed for {InputPath} to {OutputPath}", inputFile, outputPath);
- failed = true;
- continue;
- }
+ _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputFolder);
- _logger.LogInformation("ffmpeg media attachment extraction completed for {InputPath} to {OutputPath}", inputFile, outputPath);
+ throw new InvalidOperationException(
+ string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputFolder));
}
- }
- if (failed)
- {
- throw new FfmpegException(
- string.Format(CultureInfo.InvariantCulture, "ffmpeg media attachment extraction failed for {0}", inputFile));
+ _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputFolder);
}
}
- private async Task ExtractAttachment(
+ private async Task<Stream> GetAttachmentStream(
+ MediaSourceInfo mediaSource,
+ MediaAttachment mediaAttachment,
+ CancellationToken cancellationToken)
+ {
+ var attachmentPath = await ExtractAttachment(mediaSource.Path, mediaSource, mediaAttachment, cancellationToken)
+ .ConfigureAwait(false);
+ return AsyncFile.OpenRead(attachmentPath);
+ }
+
+ private async Task<string> ExtractAttachment(
string inputFile,
MediaSourceInfo mediaSource,
- int attachmentStreamIndex,
- string outputPath,
+ MediaAttachment mediaAttachment,
CancellationToken cancellationToken)
{
- using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
+ var attachmentFolderPath = _pathManager.GetAttachmentFolderPath(mediaSource.Id);
+ using (await _semaphoreLocks.LockAsync(attachmentFolderPath, cancellationToken).ConfigureAwait(false))
{
- if (!File.Exists(outputPath))
+ var attachmentPath = _pathManager.GetAttachmentPath(mediaSource.Id, mediaAttachment.FileName ?? mediaAttachment.Index.ToString(CultureInfo.InvariantCulture));
+ if (!File.Exists(attachmentPath))
{
await ExtractAttachmentInternal(
_mediaEncoder.GetInputArgument(inputFile, mediaSource),
- attachmentStreamIndex,
- outputPath,
+ mediaAttachment.Index,
+ attachmentPath,
cancellationToken).ConfigureAwait(false);
}
+
+ return attachmentPath;
}
}
@@ -510,23 +341,6 @@ namespace MediaBrowser.MediaEncoding.Attachments
_logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
}
- private string GetAttachmentCachePath(string mediaPath, MediaSourceInfo mediaSource, int attachmentStreamIndex)
- {
- string filename;
- if (mediaSource.Protocol == MediaProtocol.File)
- {
- var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
- filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
- }
- else
- {
- filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
- }
-
- var prefix = filename.AsSpan(0, 1);
- return Path.Join(_appPaths.DataPath, "attachments", prefix, filename);
- }
-
/// <inheritdoc />
public void Dispose()
{
diff --git a/MediaBrowser.MediaEncoding/Encoder/ApplePlatformHelper.cs b/MediaBrowser.MediaEncoding/Encoder/ApplePlatformHelper.cs
new file mode 100644
index 000000000..a8ff58b09
--- /dev/null
+++ b/MediaBrowser.MediaEncoding/Encoder/ApplePlatformHelper.cs
@@ -0,0 +1,87 @@
+#pragma warning disable CA1031
+
+using System;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+using Microsoft.Extensions.Logging;
+
+namespace MediaBrowser.MediaEncoding.Encoder;
+
+/// <summary>
+/// Helper class for Apple platform specific operations.
+/// </summary>
+[SupportedOSPlatform("macos")]
+public static class ApplePlatformHelper
+{
+ private static readonly string[] _av1DecodeBlacklistedCpuClass = ["M1", "M2"];
+
+ private static string GetSysctlValue(ReadOnlySpan<byte> name)
+ {
+ IntPtr length = IntPtr.Zero;
+ // Get length of the value
+ int osStatus = SysctlByName(name, IntPtr.Zero, ref length, IntPtr.Zero, 0);
+
+ if (osStatus != 0)
+ {
+ throw new NotSupportedException($"Failed to get sysctl value for {System.Text.Encoding.UTF8.GetString(name)} with error {osStatus}");
+ }
+
+ IntPtr buffer = Marshal.AllocHGlobal(length.ToInt32());
+ try
+ {
+ osStatus = SysctlByName(name, buffer, ref length, IntPtr.Zero, 0);
+ if (osStatus != 0)
+ {
+ throw new NotSupportedException($"Failed to get sysctl value for {System.Text.Encoding.UTF8.GetString(name)} with error {osStatus}");
+ }
+
+ return Marshal.PtrToStringAnsi(buffer) ?? string.Empty;
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buffer);
+ }
+ }
+
+ private static int SysctlByName(ReadOnlySpan<byte> name, IntPtr oldp, ref IntPtr oldlenp, IntPtr newp, uint newlen)
+ {
+ return NativeMethods.SysctlByName(name.ToArray(), oldp, ref oldlenp, newp, newlen);
+ }
+
+ /// <summary>
+ /// Check if the current system has hardware acceleration for AV1 decoding.
+ /// </summary>
+ /// <param name="logger">The logger used for error logging.</param>
+ /// <returns>Boolean indicates the hwaccel support.</returns>
+ public static bool HasAv1HardwareAccel(ILogger logger)
+ {
+ if (!RuntimeInformation.OSArchitecture.Equals(Architecture.Arm64))
+ {
+ return false;
+ }
+
+ try
+ {
+ string cpuBrandString = GetSysctlValue("machdep.cpu.brand_string"u8);
+ return !_av1DecodeBlacklistedCpuClass.Any(blacklistedCpuClass => cpuBrandString.Contains(blacklistedCpuClass, StringComparison.OrdinalIgnoreCase));
+ }
+ catch (NotSupportedException e)
+ {
+ logger.LogError("Error getting CPU brand string: {Message}", e.Message);
+ }
+ catch (Exception e)
+ {
+ logger.LogError("Unknown error occured: {Exception}", e);
+ }
+
+ return false;
+ }
+
+ private static class NativeMethods
+ {
+ [DllImport("libc", EntryPoint = "sysctlbyname", SetLastError = true)]
+ [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)]
+ internal static extern int SysctlByName(byte[] name, IntPtr oldp, ref IntPtr oldlenp, IntPtr newp, uint newlen);
+ }
+}
diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
index 23d9ca7ef..f4e8c39c1 100644
--- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
@@ -5,15 +5,17 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
+using System.Runtime.Versioning;
using System.Text.RegularExpressions;
+using MediaBrowser.Controller.MediaEncoding;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.MediaEncoding.Encoder
{
public partial class EncoderValidator
{
- private static readonly string[] _requiredDecoders = new[]
- {
+ private static readonly string[] _requiredDecoders =
+ [
"h264",
"hevc",
"vp8",
@@ -55,10 +57,10 @@ namespace MediaBrowser.MediaEncoding.Encoder
"vp8_rkmpp",
"vp9_rkmpp",
"av1_rkmpp"
- };
+ ];
- private static readonly string[] _requiredEncoders = new[]
- {
+ private static readonly string[] _requiredEncoders =
+ [
"libx264",
"libx265",
"libsvtav1",
@@ -95,10 +97,10 @@ namespace MediaBrowser.MediaEncoding.Encoder
"h264_rkmpp",
"hevc_rkmpp",
"mjpeg_rkmpp"
- };
+ ];
- private static readonly string[] _requiredFilters = new[]
- {
+ private static readonly string[] _requiredFilters =
+ [
// sw
"alphasrc",
"zscale",
@@ -121,6 +123,8 @@ namespace MediaBrowser.MediaEncoding.Encoder
"tonemap_opencl",
"overlay_opencl",
"transpose_opencl",
+ "yadif_opencl",
+ "bwdif_opencl",
// vaapi
"scale_vaapi",
"deinterlace_vaapi",
@@ -146,17 +150,28 @@ namespace MediaBrowser.MediaEncoding.Encoder
"scale_rkrga",
"vpp_rkrga",
"overlay_rkrga"
+ ];
+
+ private static readonly Dictionary<FilterOptionType, (string, string)> _filterOptionsDict = new Dictionary<FilterOptionType, (string, string)>
+ {
+ { FilterOptionType.ScaleCudaFormat, ("scale_cuda", "format") },
+ { FilterOptionType.TonemapCudaName, ("tonemap_cuda", "GPU accelerated HDR to SDR tonemapping") },
+ { FilterOptionType.TonemapOpenclBt2390, ("tonemap_opencl", "bt2390") },
+ { FilterOptionType.OverlayOpenclFrameSync, ("overlay_opencl", "Action to take when encountering EOF from secondary input") },
+ { FilterOptionType.OverlayVaapiFrameSync, ("overlay_vaapi", "Action to take when encountering EOF from secondary input") },
+ { FilterOptionType.OverlayVulkanFrameSync, ("overlay_vulkan", "Action to take when encountering EOF from secondary input") },
+ { FilterOptionType.TransposeOpenclReversal, ("transpose_opencl", "rotate by half-turn") },
+ { FilterOptionType.OverlayOpenclAlphaFormat, ("overlay_opencl", "alpha_format") },
+ { FilterOptionType.OverlayCudaAlphaFormat, ("overlay_cuda", "alpha_format") }
};
- private static readonly Dictionary<int, string[]> _filterOptionsDict = new Dictionary<int, string[]>
+ private static readonly Dictionary<BitStreamFilterOptionType, (string, string)> _bsfOptionsDict = new Dictionary<BitStreamFilterOptionType, (string, string)>
{
- { 0, new string[] { "scale_cuda", "format" } },
- { 1, new string[] { "tonemap_cuda", "GPU accelerated HDR to SDR tonemapping" } },
- { 2, new string[] { "tonemap_opencl", "bt2390" } },
- { 3, new string[] { "overlay_opencl", "Action to take when encountering EOF from secondary input" } },
- { 4, new string[] { "overlay_vaapi", "Action to take when encountering EOF from secondary input" } },
- { 5, new string[] { "overlay_vulkan", "Action to take when encountering EOF from secondary input" } },
- { 6, new string[] { "transpose_opencl", "rotate by half-turn" } }
+ { BitStreamFilterOptionType.HevcMetadataRemoveDovi, ("hevc_metadata", "remove_dovi") },
+ { BitStreamFilterOptionType.HevcMetadataRemoveHdr10Plus, ("hevc_metadata", "remove_hdr10plus") },
+ { BitStreamFilterOptionType.Av1MetadataRemoveDovi, ("av1_metadata", "remove_dovi") },
+ { BitStreamFilterOptionType.Av1MetadataRemoveHdr10Plus, ("av1_metadata", "remove_hdr10plus") },
+ { BitStreamFilterOptionType.DoviRpuStrip, ("dovi_rpu", "strip") }
};
// These are the library versions that corresponds to our minimum ffmpeg version 4.4 according to the version table below
@@ -283,7 +298,11 @@ namespace MediaBrowser.MediaEncoding.Encoder
public IEnumerable<string> GetFilters() => GetFFmpegFilters();
- public IDictionary<int, bool> GetFiltersWithOption() => GetFFmpegFiltersWithOption();
+ public IDictionary<FilterOptionType, bool> GetFiltersWithOption() => _filterOptionsDict
+ .ToDictionary(item => item.Key, item => CheckFilterWithOption(item.Value.Item1, item.Value.Item2));
+
+ public IDictionary<BitStreamFilterOptionType, bool> GetBitStreamFiltersWithOption() => _bsfOptionsDict
+ .ToDictionary(item => item.Key, item => CheckBitStreamFilterWithOption(item.Value.Item1, item.Value.Item2));
public Version? GetFFmpegVersion()
{
@@ -437,6 +456,12 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
}
+ [SupportedOSPlatform("macos")]
+ public bool CheckIsVideoToolboxAv1DecodeAvailable()
+ {
+ return ApplePlatformHelper.HasAv1HardwareAccel(_logger);
+ }
+
private IEnumerable<string> GetHwaccelTypes()
{
string? output = null;
@@ -451,10 +476,10 @@ namespace MediaBrowser.MediaEncoding.Encoder
if (string.IsNullOrWhiteSpace(output))
{
- return Enumerable.Empty<string>();
+ return [];
}
- var found = output.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Skip(1).Distinct().ToList();
+ var found = output.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries).Skip(1).Distinct().ToList();
_logger.LogInformation("Available hwaccel types: {Types}", found);
return found;
@@ -488,6 +513,34 @@ namespace MediaBrowser.MediaEncoding.Encoder
return false;
}
+ public bool CheckBitStreamFilterWithOption(string filter, string option)
+ {
+ if (string.IsNullOrEmpty(filter) || string.IsNullOrEmpty(option))
+ {
+ return false;
+ }
+
+ string output;
+ try
+ {
+ output = GetProcessOutput(_encoderPath, "-h bsf=" + filter, false, null);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error detecting the given bit stream filter");
+ return false;
+ }
+
+ if (output.Contains("Bit stream filter " + filter, StringComparison.Ordinal))
+ {
+ return output.Contains(option, StringComparison.Ordinal);
+ }
+
+ _logger.LogWarning("Bit stream filter: {Name} with option {Option} is not available", filter, option);
+
+ return false;
+ }
+
public bool CheckSupportedRuntimeKey(string keyDesc, Version? ffmpegVersion)
{
if (string.IsNullOrEmpty(keyDesc))
@@ -516,6 +569,11 @@ namespace MediaBrowser.MediaEncoding.Encoder
return !string.IsNullOrEmpty(flag) && GetProcessExitCode(_encoderPath, $"-loglevel quiet -hwaccel_flags +{flag} -hide_banner -f lavfi -i nullsrc=s=1x1:d=100 -f null -");
}
+ public bool CheckSupportedProberOption(string option, string proberPath)
+ {
+ return !string.IsNullOrEmpty(option) && GetProcessExitCode(proberPath, $"-loglevel quiet -f lavfi -i nullsrc=s=1x1:d=1 -{option}");
+ }
+
private IEnumerable<string> GetCodecs(Codec codec)
{
string codecstr = codec == Codec.Encoder ? "encoders" : "decoders";
@@ -527,12 +585,12 @@ namespace MediaBrowser.MediaEncoding.Encoder
catch (Exception ex)
{
_logger.LogError(ex, "Error detecting available {Codec}", codecstr);
- return Enumerable.Empty<string>();
+ return [];
}
if (string.IsNullOrWhiteSpace(output))
{
- return Enumerable.Empty<string>();
+ return [];
}
var required = codec == Codec.Encoder ? _requiredEncoders : _requiredDecoders;
@@ -557,12 +615,12 @@ namespace MediaBrowser.MediaEncoding.Encoder
catch (Exception ex)
{
_logger.LogError(ex, "Error detecting available filters");
- return Enumerable.Empty<string>();
+ return [];
}
if (string.IsNullOrWhiteSpace(output))
{
- return Enumerable.Empty<string>();
+ return [];
}
var found = FilterRegex()
@@ -575,20 +633,6 @@ namespace MediaBrowser.MediaEncoding.Encoder
return found;
}
- private Dictionary<int, bool> GetFFmpegFiltersWithOption()
- {
- Dictionary<int, bool> dict = new Dictionary<int, bool>();
- for (int i = 0; i < _filterOptionsDict.Count; i++)
- {
- if (_filterOptionsDict.TryGetValue(i, out var val) && val.Length == 2)
- {
- dict.Add(i, CheckFilterWithOption(val[0], val[1]));
- }
- }
-
- return dict;
- }
-
private string GetProcessOutput(string path, string arguments, bool readStdErr, string? testKey)
{
var redirectStandardIn = !string.IsNullOrEmpty(testKey);
diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
index 14cf869f9..2eb647e26 100644
--- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
@@ -72,10 +72,12 @@ namespace MediaBrowser.MediaEncoding.Encoder
private List<string> _decoders = new List<string>();
private List<string> _hwaccels = new List<string>();
private List<string> _filters = new List<string>();
- private IDictionary<int, bool> _filtersWithOption = new Dictionary<int, bool>();
+ private IDictionary<FilterOptionType, bool> _filtersWithOption = new Dictionary<FilterOptionType, bool>();
+ private IDictionary<BitStreamFilterOptionType, bool> _bitStreamFiltersWithOption = new Dictionary<BitStreamFilterOptionType, bool>();
private bool _isPkeyPauseSupported = false;
private bool _isLowPriorityHwDecodeSupported = false;
+ private bool _proberSupportsFirstVideoFrame = false;
private bool _isVaapiDeviceAmd = false;
private bool _isVaapiDeviceInteliHD = false;
@@ -83,6 +85,8 @@ namespace MediaBrowser.MediaEncoding.Encoder
private bool _isVaapiDeviceSupportVulkanDrmModifier = false;
private bool _isVaapiDeviceSupportVulkanDrmInterop = false;
+ private bool _isVideoToolboxAv1DecodeAvailable = false;
+
private static string[] _vulkanImageDrmFmtModifierExts =
{
"VK_EXT_image_drm_format_modifier",
@@ -159,6 +163,8 @@ namespace MediaBrowser.MediaEncoding.Encoder
/// <inheritdoc />
public bool IsVaapiDeviceSupportVulkanDrmInterop => _isVaapiDeviceSupportVulkanDrmInterop;
+ public bool IsVideoToolboxAv1DecodeAvailable => _isVideoToolboxAv1DecodeAvailable;
+
[GeneratedRegex(@"[^\/\\]+?(\.[^\/\\\n.]+)?$")]
private static partial Regex FfprobePathRegex();
@@ -218,6 +224,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
SetAvailableEncoders(validator.GetEncoders());
SetAvailableFilters(validator.GetFilters());
SetAvailableFiltersWithOption(validator.GetFiltersWithOption());
+ SetAvailableBitStreamFiltersWithOption(validator.GetBitStreamFiltersWithOption());
SetAvailableHwaccels(validator.GetHwaccels());
SetMediaEncoderVersion(validator);
@@ -225,6 +232,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
_isPkeyPauseSupported = validator.CheckSupportedRuntimeKey("p pause transcoding", _ffmpegVersion);
_isLowPriorityHwDecodeSupported = validator.CheckSupportedHwaccelFlag("low_priority");
+ _proberSupportsFirstVideoFrame = validator.CheckSupportedProberOption("only_first_vframe", _ffprobePath);
// Check the Vaapi device vendor
if (OperatingSystem.IsLinux()
@@ -261,6 +269,12 @@ namespace MediaBrowser.MediaEncoding.Encoder
_logger.LogInformation("VAAPI device {RenderNodePath} supports Vulkan DRM interop", options.VaapiDevice);
}
}
+
+ // Check if VideoToolbox supports AV1 decode
+ if (OperatingSystem.IsMacOS() && SupportsHwaccel("videotoolbox"))
+ {
+ _isVideoToolboxAv1DecodeAvailable = validator.CheckIsVideoToolboxAv1DecodeAvailable();
+ }
}
_logger.LogInformation("FFmpeg: {FfmpegPath}", _ffmpegPath ?? string.Empty);
@@ -327,11 +341,16 @@ namespace MediaBrowser.MediaEncoding.Encoder
_filters = list.ToList();
}
- public void SetAvailableFiltersWithOption(IDictionary<int, bool> dict)
+ public void SetAvailableFiltersWithOption(IDictionary<FilterOptionType, bool> dict)
{
_filtersWithOption = dict;
}
+ public void SetAvailableBitStreamFiltersWithOption(IDictionary<BitStreamFilterOptionType, bool> dict)
+ {
+ _bitStreamFiltersWithOption = dict;
+ }
+
public void SetMediaEncoderVersion(EncoderValidator validator)
{
_ffmpegVersion = validator.GetFFmpegVersion();
@@ -364,12 +383,12 @@ namespace MediaBrowser.MediaEncoding.Encoder
/// <inheritdoc />
public bool SupportsFilterWithOption(FilterOptionType option)
{
- if (_filtersWithOption.TryGetValue((int)option, out var val))
- {
- return val;
- }
+ return _filtersWithOption.TryGetValue(option, out var val) && val;
+ }
- return false;
+ public bool SupportsBitStreamFilterWithOption(BitStreamFilterOptionType option)
+ {
+ return _bitStreamFiltersWithOption.TryGetValue(option, out var val) && val;
}
public bool CanEncodeToAudioCodec(string codec)
@@ -491,6 +510,12 @@ namespace MediaBrowser.MediaEncoding.Encoder
var args = extractChapters
? "{0} -i {1} -threads {2} -v warning -print_format json -show_streams -show_chapters -show_format"
: "{0} -i {1} -threads {2} -v warning -print_format json -show_streams -show_format";
+
+ if (_proberSupportsFirstVideoFrame)
+ {
+ args += " -show_frames -only_first_vframe";
+ }
+
args = string.Format(CultureInfo.InvariantCulture, args, probeSizeArgument, inputPath, _threads).Trim();
var process = new Process
@@ -512,7 +537,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
EnableRaisingEvents = true
};
- _logger.LogInformation("Starting {ProcessFileName} with args {ProcessArgs}", _ffprobePath, args);
+ _logger.LogDebug("Starting {ProcessFileName} with args {ProcessArgs}", _ffprobePath, args);
var memoryStream = new MemoryStream();
await using (memoryStream.ConfigureAwait(false))
@@ -612,7 +637,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
catch (Exception ex)
{
- _logger.LogError(ex, "I-frame image extraction failed, will attempt standard way. Input: {Arguments}", inputArgument);
+ _logger.LogWarning(ex, "I-frame image extraction failed, will attempt standard way. Input: {Arguments}", inputArgument);
}
}
@@ -690,13 +715,11 @@ namespace MediaBrowser.MediaEncoding.Encoder
filters.Add(scaler);
- // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case.
- // mpegts need larger batch size otherwise the corrupted thumbnail will be created. Larger batch size will lower the processing speed.
+ // Use ffmpeg to sample N frames and pick the best thumbnail. Have a fall back just in case.
var enableThumbnail = !useTradeoff && useIFrame && !string.Equals("wtv", container, StringComparison.OrdinalIgnoreCase);
if (enableThumbnail)
{
- var useLargerBatchSize = string.Equals("mpegts", container, StringComparison.OrdinalIgnoreCase);
- filters.Add("thumbnail=n=" + (useLargerBatchSize ? "50" : "24"));
+ filters.Add("thumbnail=n=24");
}
// Use SW tonemap on HDR video stream only when the zscale or tonemapx filter is available.
@@ -709,25 +732,37 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
var peak = videoStream.VideoRangeType == VideoRangeType.DOVI ? "400" : "100";
enableHdrExtraction = true;
- filters.Add($"tonemapx=tonemap=bt2390:desat=0:peak={peak}:t=bt709:m=bt709:p=bt709:format=yuv420p");
+ filters.Add($"tonemapx=tonemap=bt2390:desat=0:peak={peak}:t=bt709:m=bt709:p=bt709:format=yuv420p:range=full");
}
else if (SupportsFilter("zscale") && videoStream.VideoRangeType != VideoRangeType.DOVI)
{
enableHdrExtraction = true;
- filters.Add("zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0:peak=100,zscale=t=bt709:m=bt709,format=yuv420p");
+ filters.Add("zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0:peak=100,zscale=t=bt709:m=bt709:out_range=full,format=yuv420p");
}
}
var vf = string.Join(',', filters);
var mapArg = imageStreamIndex.HasValue ? (" -map 0:" + imageStreamIndex.Value.ToString(CultureInfo.InvariantCulture)) : string.Empty;
- var args = string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads {4} -v quiet -vframes 1 -vf {2}{5} -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, _threads, isAudio ? string.Empty : GetImageResolutionParameter());
+ var args = string.Format(
+ CultureInfo.InvariantCulture,
+ "-i {0}{1} -threads {2} -v quiet -vframes 1 -vf {3}{4}{5} -f image2 \"{6}\"",
+ inputPath,
+ mapArg,
+ _threads,
+ vf,
+ isAudio ? string.Empty : GetImageResolutionParameter(),
+ EncodingHelper.GetVideoSyncOption("-1", EncoderVersion), // auto decide fps mode
+ tempExtractPath);
if (offset.HasValue)
{
args = string.Format(CultureInfo.InvariantCulture, "-ss {0} ", GetTimeParameter(offset.Value)) + args;
}
- if (useIFrame && useTradeoff)
+ // The mpegts demuxer cannot seek to keyframes, so we have to let the
+ // decoder discard non-keyframes, which may contain corrupted images.
+ var seekMpegTs = offset.HasValue && string.Equals("mpegts", container, StringComparison.OrdinalIgnoreCase);
+ if (useIFrame && (useTradeoff || seekMpegTs))
{
args = "-skip_frame nokey " + args;
}
diff --git a/MediaBrowser.MediaEncoding/Probing/InternalMediaInfoResult.cs b/MediaBrowser.MediaEncoding/Probing/InternalMediaInfoResult.cs
index d4d153b08..53eea64db 100644
--- a/MediaBrowser.MediaEncoding/Probing/InternalMediaInfoResult.cs
+++ b/MediaBrowser.MediaEncoding/Probing/InternalMediaInfoResult.cs
@@ -30,5 +30,12 @@ namespace MediaBrowser.MediaEncoding.Probing
/// <value>The chapters.</value>
[JsonPropertyName("chapters")]
public IReadOnlyList<MediaChapter> Chapters { get; set; }
+
+ /// <summary>
+ /// Gets or sets the frames.
+ /// </summary>
+ /// <value>The streams.</value>
+ [JsonPropertyName("frames")]
+ public IReadOnlyList<MediaFrameInfo> Frames { get; set; }
}
}
diff --git a/MediaBrowser.MediaEncoding/Probing/MediaFrameInfo.cs b/MediaBrowser.MediaEncoding/Probing/MediaFrameInfo.cs
new file mode 100644
index 000000000..bed4368ed
--- /dev/null
+++ b/MediaBrowser.MediaEncoding/Probing/MediaFrameInfo.cs
@@ -0,0 +1,184 @@
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.MediaEncoding.Probing;
+
+/// <summary>
+/// Class MediaFrameInfo.
+/// </summary>
+public class MediaFrameInfo
+{
+ /// <summary>
+ /// Gets or sets the media type.
+ /// </summary>
+ [JsonPropertyName("media_type")]
+ public string? MediaType { get; set; }
+
+ /// <summary>
+ /// Gets or sets the StreamIndex.
+ /// </summary>
+ [JsonPropertyName("stream_index")]
+ public int? StreamIndex { get; set; }
+
+ /// <summary>
+ /// Gets or sets the KeyFrame.
+ /// </summary>
+ [JsonPropertyName("key_frame")]
+ public int? KeyFrame { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Pts.
+ /// </summary>
+ [JsonPropertyName("pts")]
+ public long? Pts { get; set; }
+
+ /// <summary>
+ /// Gets or sets the PtsTime.
+ /// </summary>
+ [JsonPropertyName("pts_time")]
+ public string? PtsTime { get; set; }
+
+ /// <summary>
+ /// Gets or sets the BestEffortTimestamp.
+ /// </summary>
+ [JsonPropertyName("best_effort_timestamp")]
+ public long BestEffortTimestamp { get; set; }
+
+ /// <summary>
+ /// Gets or sets the BestEffortTimestampTime.
+ /// </summary>
+ [JsonPropertyName("best_effort_timestamp_time")]
+ public string? BestEffortTimestampTime { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Duration.
+ /// </summary>
+ [JsonPropertyName("duration")]
+ public int Duration { get; set; }
+
+ /// <summary>
+ /// Gets or sets the DurationTime.
+ /// </summary>
+ [JsonPropertyName("duration_time")]
+ public string? DurationTime { get; set; }
+
+ /// <summary>
+ /// Gets or sets the PktPos.
+ /// </summary>
+ [JsonPropertyName("pkt_pos")]
+ public string? PktPos { get; set; }
+
+ /// <summary>
+ /// Gets or sets the PktSize.
+ /// </summary>
+ [JsonPropertyName("pkt_size")]
+ public string? PktSize { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Width.
+ /// </summary>
+ [JsonPropertyName("width")]
+ public int? Width { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Height.
+ /// </summary>
+ [JsonPropertyName("height")]
+ public int? Height { get; set; }
+
+ /// <summary>
+ /// Gets or sets the CropTop.
+ /// </summary>
+ [JsonPropertyName("crop_top")]
+ public int? CropTop { get; set; }
+
+ /// <summary>
+ /// Gets or sets the CropBottom.
+ /// </summary>
+ [JsonPropertyName("crop_bottom")]
+ public int? CropBottom { get; set; }
+
+ /// <summary>
+ /// Gets or sets the CropLeft.
+ /// </summary>
+ [JsonPropertyName("crop_left")]
+ public int? CropLeft { get; set; }
+
+ /// <summary>
+ /// Gets or sets the CropRight.
+ /// </summary>
+ [JsonPropertyName("crop_right")]
+ public int? CropRight { get; set; }
+
+ /// <summary>
+ /// Gets or sets the PixFmt.
+ /// </summary>
+ [JsonPropertyName("pix_fmt")]
+ public string? PixFmt { get; set; }
+
+ /// <summary>
+ /// Gets or sets the SampleAspectRatio.
+ /// </summary>
+ [JsonPropertyName("sample_aspect_ratio")]
+ public string? SampleAspectRatio { get; set; }
+
+ /// <summary>
+ /// Gets or sets the PictType.
+ /// </summary>
+ [JsonPropertyName("pict_type")]
+ public string? PictType { get; set; }
+
+ /// <summary>
+ /// Gets or sets the InterlacedFrame.
+ /// </summary>
+ [JsonPropertyName("interlaced_frame")]
+ public int? InterlacedFrame { get; set; }
+
+ /// <summary>
+ /// Gets or sets the TopFieldFirst.
+ /// </summary>
+ [JsonPropertyName("top_field_first")]
+ public int? TopFieldFirst { get; set; }
+
+ /// <summary>
+ /// Gets or sets the RepeatPict.
+ /// </summary>
+ [JsonPropertyName("repeat_pict")]
+ public int? RepeatPict { get; set; }
+
+ /// <summary>
+ /// Gets or sets the ColorRange.
+ /// </summary>
+ [JsonPropertyName("color_range")]
+ public string? ColorRange { get; set; }
+
+ /// <summary>
+ /// Gets or sets the ColorSpace.
+ /// </summary>
+ [JsonPropertyName("color_space")]
+ public string? ColorSpace { get; set; }
+
+ /// <summary>
+ /// Gets or sets the ColorPrimaries.
+ /// </summary>
+ [JsonPropertyName("color_primaries")]
+ public string? ColorPrimaries { get; set; }
+
+ /// <summary>
+ /// Gets or sets the ColorTransfer.
+ /// </summary>
+ [JsonPropertyName("color_transfer")]
+ public string? ColorTransfer { get; set; }
+
+ /// <summary>
+ /// Gets or sets the ChromaLocation.
+ /// </summary>
+ [JsonPropertyName("chroma_location")]
+ public string? ChromaLocation { get; set; }
+
+ /// <summary>
+ /// Gets or sets the SideDataList.
+ /// </summary>
+ [JsonPropertyName("side_data_list")]
+ public IReadOnlyList<MediaFrameSideDataInfo>? SideDataList { get; set; }
+}
diff --git a/MediaBrowser.MediaEncoding/Probing/MediaFrameSideDataInfo.cs b/MediaBrowser.MediaEncoding/Probing/MediaFrameSideDataInfo.cs
new file mode 100644
index 000000000..3f7dd9a69
--- /dev/null
+++ b/MediaBrowser.MediaEncoding/Probing/MediaFrameSideDataInfo.cs
@@ -0,0 +1,16 @@
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.MediaEncoding.Probing;
+
+/// <summary>
+/// Class MediaFrameSideDataInfo.
+/// Currently only records the SideDataType for HDR10+ detection.
+/// </summary>
+public class MediaFrameSideDataInfo
+{
+ /// <summary>
+ /// Gets or sets the SideDataType.
+ /// </summary>
+ [JsonPropertyName("side_data_type")]
+ public string? SideDataType { get; set; }
+}
diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
index 6b0fd9a14..5784deacd 100644
--- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
+++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
@@ -105,8 +105,9 @@ namespace MediaBrowser.MediaEncoding.Probing
SetSize(data, info);
var internalStreams = data.Streams ?? Array.Empty<MediaStreamInfo>();
+ var internalFrames = data.Frames ?? Array.Empty<MediaFrameInfo>();
- info.MediaStreams = internalStreams.Select(s => GetMediaStream(isAudio, s, data.Format))
+ info.MediaStreams = internalStreams.Select(s => GetMediaStream(isAudio, s, data.Format, internalFrames))
.Where(i => i is not null)
// Drop subtitle streams if we don't know the codec because it will just cause failures if we don't know how to handle them
.Where(i => i.Type != MediaStreamType.Subtitle || !string.IsNullOrWhiteSpace(i.Codec))
@@ -685,8 +686,9 @@ namespace MediaBrowser.MediaEncoding.Probing
/// <param name="isAudio">if set to <c>true</c> [is info].</param>
/// <param name="streamInfo">The stream info.</param>
/// <param name="formatInfo">The format info.</param>
+ /// <param name="frameInfoList">The frame info.</param>
/// <returns>MediaStream.</returns>
- private MediaStream GetMediaStream(bool isAudio, MediaStreamInfo streamInfo, MediaFormatInfo formatInfo)
+ private MediaStream GetMediaStream(bool isAudio, MediaStreamInfo streamInfo, MediaFormatInfo formatInfo, IReadOnlyList<MediaFrameInfo> frameInfoList)
{
// These are mp4 chapters
if (string.Equals(streamInfo.CodecName, "mov_text", StringComparison.OrdinalIgnoreCase))
@@ -904,6 +906,15 @@ namespace MediaBrowser.MediaEncoding.Probing
}
}
}
+
+ var frameInfo = frameInfoList?.FirstOrDefault(i => i.StreamIndex == stream.Index);
+ if (frameInfo?.SideDataList != null)
+ {
+ if (frameInfo.SideDataList.Any(data => string.Equals(data.SideDataType, "HDR Dynamic Metadata SMPTE2094-40 (HDR10+)", StringComparison.OrdinalIgnoreCase)))
+ {
+ stream.Hdr10PlusPresentFlag = true;
+ }
+ }
}
else if (streamInfo.CodecType == CodecType.Data)
{
@@ -954,7 +965,7 @@ namespace MediaBrowser.MediaEncoding.Probing
// Get average bitrate info from tag "NUMBER_OF_BYTES" and "DURATION" if possible.
var durationInSeconds = GetRuntimeSecondsFromTags(streamInfo);
var bytes = GetNumberOfBytesFromTags(streamInfo);
- if (durationInSeconds is not null && bytes is not null)
+ if (durationInSeconds is not null && durationInSeconds.Value >= 1 && bytes is not null)
{
bps = Convert.ToInt32(bytes * 8 / durationInSeconds, CultureInfo.InvariantCulture);
if (bps > 0)
diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs
index a731d4785..777e33587 100644
--- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs
+++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs
@@ -13,10 +13,10 @@ using System.Threading;
using System.Threading.Tasks;
using AsyncKeyedLock;
using MediaBrowser.Common;
-using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Model.Dto;
@@ -31,12 +31,12 @@ namespace MediaBrowser.MediaEncoding.Subtitles
public sealed class SubtitleEncoder : ISubtitleEncoder, IDisposable
{
private readonly ILogger<SubtitleEncoder> _logger;
- private readonly IApplicationPaths _appPaths;
private readonly IFileSystem _fileSystem;
private readonly IMediaEncoder _mediaEncoder;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IMediaSourceManager _mediaSourceManager;
private readonly ISubtitleParser _subtitleParser;
+ private readonly IPathManager _pathManager;
/// <summary>
/// The _semaphoreLocks.
@@ -49,24 +49,22 @@ namespace MediaBrowser.MediaEncoding.Subtitles
public SubtitleEncoder(
ILogger<SubtitleEncoder> logger,
- IApplicationPaths appPaths,
IFileSystem fileSystem,
IMediaEncoder mediaEncoder,
IHttpClientFactory httpClientFactory,
IMediaSourceManager mediaSourceManager,
- ISubtitleParser subtitleParser)
+ ISubtitleParser subtitleParser,
+ IPathManager pathManager)
{
_logger = logger;
- _appPaths = appPaths;
_fileSystem = fileSystem;
_mediaEncoder = mediaEncoder;
_httpClientFactory = httpClientFactory;
_mediaSourceManager = mediaSourceManager;
_subtitleParser = subtitleParser;
+ _pathManager = pathManager;
}
- private string SubtitleCachePath => Path.Combine(_appPaths.DataPath, "subtitles");
-
private MemoryStream ConvertSubtitles(
Stream stream,
string inputFormat,
@@ -830,26 +828,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
private string GetSubtitleCachePath(MediaSourceInfo mediaSource, int subtitleStreamIndex, string outputSubtitleExtension)
{
- if (mediaSource.Protocol == MediaProtocol.File)
- {
- var ticksParam = string.Empty;
-
- var date = _fileSystem.GetLastWriteTimeUtc(mediaSource.Path);
-
- ReadOnlySpan<char> filename = (mediaSource.Path + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam).GetMD5() + outputSubtitleExtension;
-
- var prefix = filename.Slice(0, 1);
-
- return Path.Join(SubtitleCachePath, prefix, filename);
- }
- else
- {
- ReadOnlySpan<char> filename = (mediaSource.Path + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5() + outputSubtitleExtension;
-
- var prefix = filename.Slice(0, 1);
-
- return Path.Join(SubtitleCachePath, prefix, filename);
- }
+ return _pathManager.GetSubtitlePath(mediaSource.Id, subtitleStreamIndex, outputSubtitleExtension);
}
/// <inheritdoc />
diff --git a/MediaBrowser.MediaEncoding/Transcoding/TranscodeManager.cs b/MediaBrowser.MediaEncoding/Transcoding/TranscodeManager.cs
index c7f9cf2cc..0cda803d6 100644
--- a/MediaBrowser.MediaEncoding/Transcoding/TranscodeManager.cs
+++ b/MediaBrowser.MediaEncoding/Transcoding/TranscodeManager.cs
@@ -398,24 +398,19 @@ public sealed class TranscodeManager : ITranscodeManager, IDisposable
// If subtitles get burned in fonts may need to be extracted from the media file
if (state.SubtitleStream is not null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
{
- var attachmentPath = Path.Combine(_appPaths.CachePath, "attachments", state.MediaSource.Id);
if (state.MediaSource.VideoType == VideoType.Dvd || state.MediaSource.VideoType == VideoType.BluRay)
{
var concatPath = Path.Join(_appPaths.CachePath, "concat", state.MediaSource.Id + ".concat");
- await _attachmentExtractor.ExtractAllAttachments(concatPath, state.MediaSource, attachmentPath, cancellationTokenSource.Token).ConfigureAwait(false);
+ await _attachmentExtractor.ExtractAllAttachments(concatPath, state.MediaSource, cancellationTokenSource.Token).ConfigureAwait(false);
}
else
{
- await _attachmentExtractor.ExtractAllAttachments(state.MediaPath, state.MediaSource, attachmentPath, cancellationTokenSource.Token).ConfigureAwait(false);
+ await _attachmentExtractor.ExtractAllAttachments(state.MediaPath, state.MediaSource, cancellationTokenSource.Token).ConfigureAwait(false);
}
if (state.SubtitleStream.IsExternal && Path.GetExtension(state.SubtitleStream.Path.AsSpan()).Equals(".mks", StringComparison.OrdinalIgnoreCase))
{
- string subtitlePath = state.SubtitleStream.Path;
- string subtitlePathArgument = string.Format(CultureInfo.InvariantCulture, "file:\"{0}\"", subtitlePath.Replace("\"", "\\\"", StringComparison.Ordinal));
- string subtitleId = subtitlePath.GetMD5().ToString("N", CultureInfo.InvariantCulture);
-
- await _attachmentExtractor.ExtractAllAttachmentsExternal(subtitlePathArgument, subtitleId, attachmentPath, cancellationTokenSource.Token).ConfigureAwait(false);
+ await _attachmentExtractor.ExtractAllAttachments(state.SubtitleStream.Path, state.MediaSource, cancellationTokenSource.Token).ConfigureAwait(false);
}
}
diff --git a/MediaBrowser.Model/Branding/BrandingOptions.cs b/MediaBrowser.Model/Branding/BrandingOptions.cs
index c6580598b..5ec6b0dd4 100644
--- a/MediaBrowser.Model/Branding/BrandingOptions.cs
+++ b/MediaBrowser.Model/Branding/BrandingOptions.cs
@@ -1,5 +1,3 @@
-using System.Text.Json.Serialization;
-
namespace MediaBrowser.Model.Branding;
/// <summary>
@@ -27,10 +25,5 @@ public class BrandingOptions
/// <summary>
/// Gets or sets the splashscreen location on disk.
/// </summary>
- /// <remarks>
- /// Not served via the API.
- /// Only used to save the custom uploaded user splashscreen in the configuration file.
- /// </remarks>
- [JsonIgnore]
public string? SplashscreenLocation { get; set; }
}
diff --git a/MediaBrowser.Model/Branding/BrandingOptionsDto.cs b/MediaBrowser.Model/Branding/BrandingOptionsDto.cs
new file mode 100644
index 000000000..c0d8cb31c
--- /dev/null
+++ b/MediaBrowser.Model/Branding/BrandingOptionsDto.cs
@@ -0,0 +1,25 @@
+namespace MediaBrowser.Model.Branding;
+
+/// <summary>
+/// The branding options DTO for API use.
+/// This DTO excludes SplashscreenLocation to prevent it from being updated via API.
+/// </summary>
+public class BrandingOptionsDto
+{
+ /// <summary>
+ /// Gets or sets the login disclaimer.
+ /// </summary>
+ /// <value>The login disclaimer.</value>
+ public string? LoginDisclaimer { get; set; }
+
+ /// <summary>
+ /// Gets or sets the custom CSS.
+ /// </summary>
+ /// <value>The custom CSS.</value>
+ public string? CustomCss { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to enable the splashscreen.
+ /// </summary>
+ public bool SplashscreenEnabled { get; set; } = false;
+}
diff --git a/MediaBrowser.Model/Dlna/ConditionProcessor.cs b/MediaBrowser.Model/Dlna/ConditionProcessor.cs
index 09b966367..1b61bfe15 100644
--- a/MediaBrowser.Model/Dlna/ConditionProcessor.cs
+++ b/MediaBrowser.Model/Dlna/ConditionProcessor.cs
@@ -345,6 +345,15 @@ namespace MediaBrowser.Model.Dlna
return !condition.IsRequired;
}
+ // Special case: HDR10 also satisfies if the video is HDR10Plus
+ if (currentValue.Value == VideoRangeType.HDR10Plus)
+ {
+ if (IsConditionSatisfied(condition, VideoRangeType.HDR10))
+ {
+ return true;
+ }
+ }
+
var conditionType = condition.Condition;
if (conditionType == ProfileConditionType.EqualsAny)
{
diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs
index 806900e9a..61e04a813 100644
--- a/MediaBrowser.Model/Dlna/StreamBuilder.cs
+++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs
@@ -665,15 +665,39 @@ namespace MediaBrowser.Model.Dlna
// Collect candidate audio streams
ICollection<MediaStream> candidateAudioStreams = audioStream is null ? [] : [audioStream];
- if (!options.AudioStreamIndex.HasValue || options.AudioStreamIndex < 0)
+ // When the index is explicitly required by client or the default is specified by user, don't do any stream reselection.
+ if (!item.DefaultAudioIndexSource.HasFlag(AudioIndexSource.User) && (options.AudioStreamIndex is null or < 0))
{
- if (audioStream?.IsDefault == true)
+ // When user has no preferences allow stream selection on all streams.
+ if (item.DefaultAudioIndexSource == AudioIndexSource.None && audioStream is not null)
{
- candidateAudioStreams = item.MediaStreams.Where(stream => stream.Type == MediaStreamType.Audio && stream.IsDefault).ToArray();
+ candidateAudioStreams = item.MediaStreams.Where(stream => stream.Type == MediaStreamType.Audio).ToArray();
+ if (audioStream.IsDefault)
+ {
+ // If default is picked, only allow selection within default streams.
+ candidateAudioStreams = candidateAudioStreams.Where(stream => stream.IsDefault).ToArray();
+ }
}
- else
+
+ if (item.DefaultAudioIndexSource.HasFlag(AudioIndexSource.Language))
{
+ // If user has language preference, only allow stream selection within the same language.
candidateAudioStreams = item.MediaStreams.Where(stream => stream.Type == MediaStreamType.Audio && stream.Language == audioStream?.Language).ToArray();
+ if (item.DefaultAudioIndexSource.HasFlag(AudioIndexSource.Default))
+ {
+ var defaultStreamsInPreferredLanguage = candidateAudioStreams.Where(stream => stream.IsDefault).ToArray();
+
+ // If the user also prefers default streams, try limit selection within default tracks in the same language.
+ // If there is no default stream in the preferred language, allow selection on all default streams to match the "Play default audio track regardless of language" setting.
+ candidateAudioStreams = defaultStreamsInPreferredLanguage.Length > 0
+ ? defaultStreamsInPreferredLanguage
+ : item.MediaStreams.Where(stream => stream.Type == MediaStreamType.Audio && stream.IsDefault).ToArray();
+ }
+ }
+ else if (item.DefaultAudioIndexSource.HasFlag(AudioIndexSource.Default))
+ {
+ // If user prefers default streams, only allow stream selection on default streams.
+ candidateAudioStreams = item.MediaStreams.Where(stream => stream.Type == MediaStreamType.Audio && stream.IsDefault).ToArray();
}
}
diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs
index f9aab2d67..13acd15a3 100644
--- a/MediaBrowser.Model/Dlna/StreamInfo.cs
+++ b/MediaBrowser.Model/Dlna/StreamInfo.cs
@@ -2,6 +2,7 @@
using System;
using System.Collections.Generic;
+using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
@@ -956,12 +957,10 @@ public class StreamInfo
sb.Append(AudioStreamIndex.Value.ToString(CultureInfo.InvariantCulture));
}
- if (SubtitleStreamIndex.HasValue && SubtitleDeliveryMethod != SubtitleDeliveryMethod.External && SubtitleStreamIndex != -1)
+ if (SubtitleStreamIndex.HasValue && (AlwaysBurnInSubtitleWhenTranscoding || SubtitleDeliveryMethod != SubtitleDeliveryMethod.External) && SubtitleStreamIndex != -1)
{
sb.Append("&SubtitleStreamIndex=");
sb.Append(SubtitleStreamIndex.Value.ToString(CultureInfo.InvariantCulture));
- sb.Append("&SubtitleMethod=");
- sb.Append(SubtitleDeliveryMethod.ToString());
}
if (VideoBitrate.HasValue)
@@ -1095,17 +1094,11 @@ public class StreamInfo
sb.Append(CopyTimestamps.ToString(CultureInfo.InvariantCulture));
}
- if (RequireAvc)
- {
- sb.Append("&RequireAvc=");
- sb.Append(RequireAvc.ToString(CultureInfo.InvariantCulture));
- }
+ sb.Append("&RequireAvc=");
+ sb.Append(RequireAvc.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
- if (EnableAudioVbrEncoding)
- {
- sb.Append("EnableAudioVbrEncoding=");
- sb.Append(EnableAudioVbrEncoding.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
- }
+ sb.Append("&EnableAudioVbrEncoding=");
+ sb.Append(EnableAudioVbrEncoding.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
}
var etag = MediaSource?.ETag;
@@ -1118,7 +1111,7 @@ public class StreamInfo
if (SubtitleStreamIndex.HasValue && SubtitleDeliveryMethod != SubtitleDeliveryMethod.External)
{
sb.Append("&SubtitleMethod=");
- sb.AppendJoin(',', SubtitleDeliveryMethod);
+ sb.Append(SubtitleDeliveryMethod);
}
if (SubtitleStreamIndex.HasValue && SubtitleDeliveryMethod == SubtitleDeliveryMethod.Embed && SubtitleCodecs.Count != 0)
diff --git a/MediaBrowser.Model/Dto/BaseItemDto.cs b/MediaBrowser.Model/Dto/BaseItemDto.cs
index 7bfd8ca29..937409111 100644
--- a/MediaBrowser.Model/Dto/BaseItemDto.cs
+++ b/MediaBrowser.Model/Dto/BaseItemDto.cs
@@ -3,6 +3,7 @@
using System;
using System.Collections.Generic;
+using System.ComponentModel;
using Jellyfin.Data.Enums;
using Jellyfin.Database.Implementations.Entities;
using MediaBrowser.Model.Drawing;
@@ -550,7 +551,7 @@ namespace MediaBrowser.Model.Dto
/// Gets or sets the parent primary image item identifier.
/// </summary>
/// <value>The parent primary image item identifier.</value>
- public string ParentPrimaryImageItemId { get; set; }
+ public Guid? ParentPrimaryImageItemId { get; set; }
/// <summary>
/// Gets or sets the parent primary image tag.
@@ -586,6 +587,7 @@ namespace MediaBrowser.Model.Dto
/// Gets or sets the type of the media.
/// </summary>
/// <value>The type of the media.</value>
+ [DefaultValue(MediaType.Unknown)]
public MediaType MediaType { get; set; }
/// <summary>
diff --git a/MediaBrowser.Model/Dto/BaseItemPerson.cs b/MediaBrowser.Model/Dto/BaseItemPerson.cs
index d3bcf492d..80e2cfb08 100644
--- a/MediaBrowser.Model/Dto/BaseItemPerson.cs
+++ b/MediaBrowser.Model/Dto/BaseItemPerson.cs
@@ -1,6 +1,7 @@
#nullable disable
using System;
using System.Collections.Generic;
+using System.ComponentModel;
using System.Text.Json.Serialization;
using Jellyfin.Data.Enums;
using MediaBrowser.Model.Entities;
@@ -34,6 +35,7 @@ namespace MediaBrowser.Model.Dto
/// Gets or sets the type.
/// </summary>
/// <value>The type.</value>
+ [DefaultValue(PersonKind.Unknown)]
public PersonKind Type { get; set; }
/// <summary>
diff --git a/MediaBrowser.Model/Dto/MediaSourceInfo.cs b/MediaBrowser.Model/Dto/MediaSourceInfo.cs
index 66de18cfe..75ccdcf27 100644
--- a/MediaBrowser.Model/Dto/MediaSourceInfo.cs
+++ b/MediaBrowser.Model/Dto/MediaSourceInfo.cs
@@ -24,6 +24,7 @@ namespace MediaBrowser.Model.Dto
SupportsDirectPlay = true;
SupportsProbing = true;
UseMostCompatibleTranscodingProfile = false;
+ DefaultAudioIndexSource = AudioIndexSource.None;
}
public MediaProtocol Protocol { get; set; }
@@ -118,6 +119,9 @@ namespace MediaBrowser.Model.Dto
[JsonIgnore]
public TranscodeReason TranscodeReasons { get; set; }
+ [JsonIgnore]
+ public AudioIndexSource DefaultAudioIndexSource { get; set; }
+
public int? DefaultAudioStreamIndex { get; set; }
public int? DefaultSubtitleStreamIndex { get; set; }
diff --git a/MediaBrowser.Model/Dto/MetadataEditorInfo.cs b/MediaBrowser.Model/Dto/MetadataEditorInfo.cs
index a3035bf61..2f3a5d117 100644
--- a/MediaBrowser.Model/Dto/MetadataEditorInfo.cs
+++ b/MediaBrowser.Model/Dto/MetadataEditorInfo.cs
@@ -1,35 +1,55 @@
-#pragma warning disable CS1591
-
-using System;
using System.Collections.Generic;
using Jellyfin.Data.Enums;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Providers;
-namespace MediaBrowser.Model.Dto
+namespace MediaBrowser.Model.Dto;
+
+/// <summary>
+/// A class representing metadata editor information.
+/// </summary>
+public class MetadataEditorInfo
{
- public class MetadataEditorInfo
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MetadataEditorInfo"/> class.
+ /// </summary>
+ public MetadataEditorInfo()
{
- public MetadataEditorInfo()
- {
- ParentalRatingOptions = Array.Empty<ParentalRating>();
- Countries = Array.Empty<CountryInfo>();
- Cultures = Array.Empty<CultureDto>();
- ExternalIdInfos = Array.Empty<ExternalIdInfo>();
- ContentTypeOptions = Array.Empty<NameValuePair>();
- }
-
- public IReadOnlyList<ParentalRating> ParentalRatingOptions { get; set; }
-
- public IReadOnlyList<CountryInfo> Countries { get; set; }
-
- public IReadOnlyList<CultureDto> Cultures { get; set; }
-
- public IReadOnlyList<ExternalIdInfo> ExternalIdInfos { get; set; }
-
- public CollectionType? ContentType { get; set; }
-
- public IReadOnlyList<NameValuePair> ContentTypeOptions { get; set; }
+ ParentalRatingOptions = [];
+ Countries = [];
+ Cultures = [];
+ ExternalIdInfos = [];
+ ContentTypeOptions = [];
}
+
+ /// <summary>
+ /// Gets or sets the parental rating options.
+ /// </summary>
+ public IReadOnlyList<ParentalRating> ParentalRatingOptions { get; set; }
+
+ /// <summary>
+ /// Gets or sets the countries.
+ /// </summary>
+ public IReadOnlyList<CountryInfo> Countries { get; set; }
+
+ /// <summary>
+ /// Gets or sets the cultures.
+ /// </summary>
+ public IReadOnlyList<CultureDto> Cultures { get; set; }
+
+ /// <summary>
+ /// Gets or sets the external id infos.
+ /// </summary>
+ public IReadOnlyList<ExternalIdInfo> ExternalIdInfos { get; set; }
+
+ /// <summary>
+ /// Gets or sets the content type.
+ /// </summary>
+ public CollectionType? ContentType { get; set; }
+
+ /// <summary>
+ /// Gets or sets the content type options.
+ /// </summary>
+ public IReadOnlyList<NameValuePair> ContentTypeOptions { get; set; }
}
diff --git a/MediaBrowser.Model/Entities/MediaAttachment.cs b/MediaBrowser.Model/Entities/MediaAttachment.cs
index 34e3eabc9..f8f7ad0f9 100644
--- a/MediaBrowser.Model/Entities/MediaAttachment.cs
+++ b/MediaBrowser.Model/Entities/MediaAttachment.cs
@@ -1,51 +1,49 @@
-#nullable disable
-namespace MediaBrowser.Model.Entities
+namespace MediaBrowser.Model.Entities;
+
+/// <summary>
+/// Class MediaAttachment.
+/// </summary>
+public class MediaAttachment
{
/// <summary>
- /// Class MediaAttachment.
+ /// Gets or sets the codec.
/// </summary>
- public class MediaAttachment
- {
- /// <summary>
- /// Gets or sets the codec.
- /// </summary>
- /// <value>The codec.</value>
- public string Codec { get; set; }
+ /// <value>The codec.</value>
+ public string? Codec { get; set; }
- /// <summary>
- /// Gets or sets the codec tag.
- /// </summary>
- /// <value>The codec tag.</value>
- public string CodecTag { get; set; }
+ /// <summary>
+ /// Gets or sets the codec tag.
+ /// </summary>
+ /// <value>The codec tag.</value>
+ public string? CodecTag { get; set; }
- /// <summary>
- /// Gets or sets the comment.
- /// </summary>
- /// <value>The comment.</value>
- public string Comment { get; set; }
+ /// <summary>
+ /// Gets or sets the comment.
+ /// </summary>
+ /// <value>The comment.</value>
+ public string? Comment { get; set; }
- /// <summary>
- /// Gets or sets the index.
- /// </summary>
- /// <value>The index.</value>
- public int Index { get; set; }
+ /// <summary>
+ /// Gets or sets the index.
+ /// </summary>
+ /// <value>The index.</value>
+ public int Index { get; set; }
- /// <summary>
- /// Gets or sets the filename.
- /// </summary>
- /// <value>The filename.</value>
- public string FileName { get; set; }
+ /// <summary>
+ /// Gets or sets the filename.
+ /// </summary>
+ /// <value>The filename.</value>
+ public string? FileName { get; set; }
- /// <summary>
- /// Gets or sets the MIME type.
- /// </summary>
- /// <value>The MIME type.</value>
- public string MimeType { get; set; }
+ /// <summary>
+ /// Gets or sets the MIME type.
+ /// </summary>
+ /// <value>The MIME type.</value>
+ public string? MimeType { get; set; }
- /// <summary>
- /// Gets or sets the delivery URL.
- /// </summary>
- /// <value>The delivery URL.</value>
- public string DeliveryUrl { get; set; }
- }
+ /// <summary>
+ /// Gets or sets the delivery URL.
+ /// </summary>
+ /// <value>The delivery URL.</value>
+ public string? DeliveryUrl { get; set; }
}
diff --git a/MediaBrowser.Model/Entities/MediaStream.cs b/MediaBrowser.Model/Entities/MediaStream.cs
index 400768ef3..5c8f37fcd 100644
--- a/MediaBrowser.Model/Entities/MediaStream.cs
+++ b/MediaBrowser.Model/Entities/MediaStream.cs
@@ -2,6 +2,7 @@
#pragma warning disable CS1591
using System;
+using System.Collections.Frozen;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
@@ -153,10 +154,13 @@ namespace MediaBrowser.Model.Entities
/// <value>The title.</value>
public string Title { get; set; }
+ public bool? Hdr10PlusPresentFlag { get; set; }
+
/// <summary>
/// Gets the video range.
/// </summary>
/// <value>The video range.</value>
+ [DefaultValue(VideoRange.Unknown)]
public VideoRange VideoRange
{
get
@@ -171,6 +175,7 @@ namespace MediaBrowser.Model.Entities
/// Gets the video range type.
/// </summary>
/// <value>The video range type.</value>
+ [DefaultValue(VideoRangeType.Unknown)]
public VideoRangeType VideoRangeType
{
get
@@ -268,7 +273,7 @@ namespace MediaBrowser.Model.Entities
// Do not display the language code in display titles if unset or set to a special code. Show it in all other cases (possibly expanded).
if (!string.IsNullOrEmpty(Language) && !_specialCodes.Contains(Language, StringComparison.OrdinalIgnoreCase))
{
- // Get full language string i.e. eng -> English. Will not work for some languages which use ISO 639-2/B instead of /T codes.
+ // Get full language string i.e. eng -> English.
string fullLanguage = CultureInfo
.GetCultures(CultureTypes.NeutralCultures)
.FirstOrDefault(r => r.ThreeLetterISOLanguageName.Equals(Language, StringComparison.OrdinalIgnoreCase))
@@ -371,7 +376,7 @@ namespace MediaBrowser.Model.Entities
if (!string.IsNullOrEmpty(Language))
{
- // Get full language string i.e. eng -> English. Will not work for some languages which use ISO 639-2/B instead of /T codes.
+ // Get full language string i.e. eng -> English.
string fullLanguage = CultureInfo
.GetCultures(CultureTypes.NeutralCultures)
.FirstOrDefault(r => r.ThreeLetterISOLanguageName.Equals(Language, StringComparison.OrdinalIgnoreCase))
@@ -778,8 +783,8 @@ namespace MediaBrowser.Model.Entities
var blPresentFlag = BlPresentFlag == 1;
var dvBlCompatId = DvBlSignalCompatibilityId;
- var isDoViProfile = dvProfile == 5 || dvProfile == 7 || dvProfile == 8 || dvProfile == 10;
- var isDoViFlag = rpuPresentFlag && blPresentFlag && (dvBlCompatId == 0 || dvBlCompatId == 1 || dvBlCompatId == 4 || dvBlCompatId == 2 || dvBlCompatId == 6);
+ var isDoViProfile = dvProfile is 5 or 7 or 8 or 10;
+ var isDoViFlag = rpuPresentFlag && blPresentFlag && dvBlCompatId is 0 or 1 or 4 or 2 or 6;
if ((isDoViProfile && isDoViFlag)
|| string.Equals(codecTag, "dovi", StringComparison.OrdinalIgnoreCase)
@@ -787,7 +792,7 @@ namespace MediaBrowser.Model.Entities
|| string.Equals(codecTag, "dvhe", StringComparison.OrdinalIgnoreCase)
|| string.Equals(codecTag, "dav1", StringComparison.OrdinalIgnoreCase))
{
- return dvProfile switch
+ var dvRangeSet = dvProfile switch
{
5 => (VideoRange.HDR, VideoRangeType.DOVI),
8 => dvBlCompatId switch
@@ -795,32 +800,40 @@ namespace MediaBrowser.Model.Entities
1 => (VideoRange.HDR, VideoRangeType.DOVIWithHDR10),
4 => (VideoRange.HDR, VideoRangeType.DOVIWithHLG),
2 => (VideoRange.SDR, VideoRangeType.DOVIWithSDR),
- // While not in Dolby Spec, Profile 8 CCid 6 media are possible to create, and since CCid 6 stems from Bluray (Profile 7 originally) an HDR10 base layer is guaranteed to exist.
- 6 => (VideoRange.HDR, VideoRangeType.DOVIWithHDR10),
- // There is no other case to handle here as per Dolby Spec. Default case included for completeness and linting purposes
- _ => (VideoRange.SDR, VideoRangeType.SDR)
+ // Out of Dolby Spec files should be marked as invalid
+ _ => (VideoRange.HDR, VideoRangeType.DOVIInvalid)
},
- 7 => (VideoRange.HDR, VideoRangeType.HDR10),
+ 7 => (VideoRange.HDR, VideoRangeType.DOVIWithEL),
10 => dvBlCompatId switch
{
0 => (VideoRange.HDR, VideoRangeType.DOVI),
1 => (VideoRange.HDR, VideoRangeType.DOVIWithHDR10),
2 => (VideoRange.SDR, VideoRangeType.DOVIWithSDR),
4 => (VideoRange.HDR, VideoRangeType.DOVIWithHLG),
- // While not in Dolby Spec, Profile 8 CCid 6 media are possible to create, and since CCid 6 stems from Bluray (Profile 7 originally) an HDR10 base layer is guaranteed to exist.
- 6 => (VideoRange.HDR, VideoRangeType.DOVIWithHDR10),
- // There is no other case to handle here as per Dolby Spec. Default case included for completeness and linting purposes
- _ => (VideoRange.SDR, VideoRangeType.SDR)
+ // Out of Dolby Spec files should be marked as invalid
+ _ => (VideoRange.HDR, VideoRangeType.DOVIInvalid)
},
_ => (VideoRange.SDR, VideoRangeType.SDR)
};
+
+ if (Hdr10PlusPresentFlag == true)
+ {
+ return dvRangeSet.Item2 switch
+ {
+ VideoRangeType.DOVIWithHDR10 => (VideoRange.HDR, VideoRangeType.DOVIWithHDR10Plus),
+ VideoRangeType.DOVIWithEL => (VideoRange.HDR, VideoRangeType.DOVIWithELHDR10Plus),
+ _ => dvRangeSet
+ };
+ }
+
+ return dvRangeSet;
}
var colorTransfer = ColorTransfer;
if (string.Equals(colorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase))
{
- return (VideoRange.HDR, VideoRangeType.HDR10);
+ return Hdr10PlusPresentFlag == true ? (VideoRange.HDR, VideoRangeType.HDR10Plus) : (VideoRange.HDR, VideoRangeType.HDR10);
}
else if (string.Equals(colorTransfer, "arib-std-b67", StringComparison.OrdinalIgnoreCase))
{
diff --git a/MediaBrowser.Model/Entities/ParentalRating.cs b/MediaBrowser.Model/Entities/ParentalRating.cs
index c92640818..4f1198902 100644
--- a/MediaBrowser.Model/Entities/ParentalRating.cs
+++ b/MediaBrowser.Model/Entities/ParentalRating.cs
@@ -1,33 +1,40 @@
-#nullable disable
-#pragma warning disable CS1591
+namespace MediaBrowser.Model.Entities;
-namespace MediaBrowser.Model.Entities
+/// <summary>
+/// Class ParentalRating.
+/// </summary>
+public class ParentalRating
{
/// <summary>
- /// Class ParentalRating.
+ /// Initializes a new instance of the <see cref="ParentalRating"/> class.
/// </summary>
- public class ParentalRating
+ /// <param name="name">The name.</param>
+ /// <param name="score">The score.</param>
+ public ParentalRating(string name, ParentalRatingScore? score)
{
- public ParentalRating()
- {
- }
+ Name = name;
+ Value = score?.Score;
+ RatingScore = score;
+ }
- public ParentalRating(string name, int? value)
- {
- Name = name;
- Value = value;
- }
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name { get; set; }
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
+ /// <summary>
+ /// Gets or sets the value.
+ /// </summary>
+ /// <value>The value.</value>
+ /// <remarks>
+ /// Deprecated.
+ /// </remarks>
+ public int? Value { get; set; }
- /// <summary>
- /// Gets or sets the value.
- /// </summary>
- /// <value>The value.</value>
- public int? Value { get; set; }
- }
+ /// <summary>
+ /// Gets or sets the rating score.
+ /// </summary>
+ /// <value>The rating score.</value>
+ public ParentalRatingScore? RatingScore { get; set; }
}
diff --git a/MediaBrowser.Model/Entities/ParentalRatingEntry.cs b/MediaBrowser.Model/Entities/ParentalRatingEntry.cs
new file mode 100644
index 000000000..69be74ac0
--- /dev/null
+++ b/MediaBrowser.Model/Entities/ParentalRatingEntry.cs
@@ -0,0 +1,22 @@
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.Model.Entities;
+
+/// <summary>
+/// A class representing an parental rating entry.
+/// </summary>
+public class ParentalRatingEntry
+{
+ /// <summary>
+ /// Gets or sets the rating strings.
+ /// </summary>
+ [JsonPropertyName("ratingStrings")]
+ public required IReadOnlyList<string> RatingStrings { get; set; }
+
+ /// <summary>
+ /// Gets or sets the score.
+ /// </summary>
+ [JsonPropertyName("ratingScore")]
+ public required ParentalRatingScore RatingScore { get; set; }
+}
diff --git a/MediaBrowser.Model/Entities/ParentalRatingScore.cs b/MediaBrowser.Model/Entities/ParentalRatingScore.cs
new file mode 100644
index 000000000..b9bb99685
--- /dev/null
+++ b/MediaBrowser.Model/Entities/ParentalRatingScore.cs
@@ -0,0 +1,32 @@
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.Model.Entities;
+
+/// <summary>
+/// A class representing an parental rating score.
+/// </summary>
+public class ParentalRatingScore
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ParentalRatingScore"/> class.
+ /// </summary>
+ /// <param name="score">The score.</param>
+ /// <param name="subScore">The sub score.</param>
+ public ParentalRatingScore(int score, int? subScore)
+ {
+ Score = score;
+ SubScore = subScore;
+ }
+
+ /// <summary>
+ /// Gets or sets the score.
+ /// </summary>
+ [JsonPropertyName("score")]
+ public int Score { get; set; }
+
+ /// <summary>
+ /// Gets or sets the sub score.
+ /// </summary>
+ [JsonPropertyName("subScore")]
+ public int? SubScore { get; set; }
+}
diff --git a/MediaBrowser.Model/Entities/ParentalRatingSystem.cs b/MediaBrowser.Model/Entities/ParentalRatingSystem.cs
new file mode 100644
index 000000000..b452f2901
--- /dev/null
+++ b/MediaBrowser.Model/Entities/ParentalRatingSystem.cs
@@ -0,0 +1,28 @@
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.Model.Entities;
+
+/// <summary>
+/// A class representing a parental rating system.
+/// </summary>
+public class ParentalRatingSystem
+{
+ /// <summary>
+ /// Gets or sets the country code.
+ /// </summary>
+ [JsonPropertyName("countryCode")]
+ public required string CountryCode { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether sub scores are supported.
+ /// </summary>
+ [JsonPropertyName("supportsSubScores")]
+ public bool SupportsSubScores { get; set; }
+
+ /// <summary>
+ /// Gets or sets the ratings.
+ /// </summary>
+ [JsonPropertyName("ratings")]
+ public IReadOnlyList<ParentalRatingEntry>? Ratings { get; set; }
+}
diff --git a/MediaBrowser.Model/Extensions/ContainerHelper.cs b/MediaBrowser.Model/Extensions/ContainerHelper.cs
index 39e5358ba..848cc2f62 100644
--- a/MediaBrowser.Model/Extensions/ContainerHelper.cs
+++ b/MediaBrowser.Model/Extensions/ContainerHelper.cs
@@ -21,7 +21,7 @@ public static class ContainerHelper
public static bool ContainsContainer(string? profileContainers, string? inputContainer)
{
var isNegativeList = false;
- if (profileContainers != null && profileContainers.StartsWith('-'))
+ if (profileContainers is not null && profileContainers.StartsWith('-'))
{
isNegativeList = true;
profileContainers = profileContainers[1..];
@@ -42,7 +42,7 @@ public static class ContainerHelper
public static bool ContainsContainer(string? profileContainers, ReadOnlySpan<char> inputContainer)
{
var isNegativeList = false;
- if (profileContainers != null && profileContainers.StartsWith('-'))
+ if (profileContainers is not null && profileContainers.StartsWith('-'))
{
isNegativeList = true;
profileContainers = profileContainers[1..];
diff --git a/MediaBrowser.Model/Extensions/EnumerableExtensions.cs b/MediaBrowser.Model/Extensions/EnumerableExtensions.cs
index 8963bdb73..94f425229 100644
--- a/MediaBrowser.Model/Extensions/EnumerableExtensions.cs
+++ b/MediaBrowser.Model/Extensions/EnumerableExtensions.cs
@@ -50,7 +50,7 @@ namespace MediaBrowser.Model.Extensions
return 0;
})
- .ThenByDescending(i => i.CommunityRating ?? 0)
+ .ThenByDescending(i => Math.Round(i.CommunityRating ?? 0, 1) )
.ThenByDescending(i => i.VoteCount ?? 0);
}
}
diff --git a/MediaBrowser.Model/Globalization/ILocalizationManager.cs b/MediaBrowser.Model/Globalization/ILocalizationManager.cs
index 20deaa505..f6e65028e 100644
--- a/MediaBrowser.Model/Globalization/ILocalizationManager.cs
+++ b/MediaBrowser.Model/Globalization/ILocalizationManager.cs
@@ -1,65 +1,73 @@
using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
using MediaBrowser.Model.Entities;
-namespace MediaBrowser.Model.Globalization
+namespace MediaBrowser.Model.Globalization;
+
+/// <summary>
+/// Interface ILocalizationManager.
+/// </summary>
+public interface ILocalizationManager
{
/// <summary>
- /// Interface ILocalizationManager.
+ /// Gets the cultures.
/// </summary>
- public interface ILocalizationManager
- {
- /// <summary>
- /// Gets the cultures.
- /// </summary>
- /// <returns><see cref="IEnumerable{CultureDto}" />.</returns>
- IEnumerable<CultureDto> GetCultures();
+ /// <returns><see cref="IEnumerable{CultureDto}" />.</returns>
+ IEnumerable<CultureDto> GetCultures();
- /// <summary>
- /// Gets the countries.
- /// </summary>
- /// <returns><see cref="IEnumerable{CountryInfo}" />.</returns>
- IEnumerable<CountryInfo> GetCountries();
+ /// <summary>
+ /// Gets the countries.
+ /// </summary>
+ /// <returns><see cref="IReadOnlyList{CountryInfo}" />.</returns>
+ IReadOnlyList<CountryInfo> GetCountries();
- /// <summary>
- /// Gets the parental ratings.
- /// </summary>
- /// <returns><see cref="IEnumerable{ParentalRating}" />.</returns>
- IEnumerable<ParentalRating> GetParentalRatings();
+ /// <summary>
+ /// Gets the parental ratings.
+ /// </summary>
+ /// <returns><see cref="IReadOnlyList{ParentalRating}" />.</returns>
+ IReadOnlyList<ParentalRating> GetParentalRatings();
- /// <summary>
- /// Gets the rating level.
- /// </summary>
- /// <param name="rating">The rating.</param>
- /// <param name="countryCode">The optional two letter ISO language string.</param>
- /// <returns><see cref="int" /> or <c>null</c>.</returns>
- int? GetRatingLevel(string rating, string? countryCode = null);
+ /// <summary>
+ /// Gets the rating level.
+ /// </summary>
+ /// <param name="rating">The rating.</param>
+ /// <param name="countryCode">The optional two letter ISO language string.</param>
+ /// <returns><see cref="ParentalRatingScore" /> or <c>null</c>.</returns>
+ ParentalRatingScore? GetRatingScore(string rating, string? countryCode = null);
+
+ /// <summary>
+ /// Gets the localized string.
+ /// </summary>
+ /// <param name="phrase">The phrase.</param>
+ /// <param name="culture">The culture.</param>
+ /// <returns><see cref="string" />.</returns>
+ string GetLocalizedString(string phrase, string culture);
- /// <summary>
- /// Gets the localized string.
- /// </summary>
- /// <param name="phrase">The phrase.</param>
- /// <param name="culture">The culture.</param>
- /// <returns><see cref="string" />.</returns>
- string GetLocalizedString(string phrase, string culture);
+ /// <summary>
+ /// Gets the localized string.
+ /// </summary>
+ /// <param name="phrase">The phrase.</param>
+ /// <returns>System.String.</returns>
+ string GetLocalizedString(string phrase);
- /// <summary>
- /// Gets the localized string.
- /// </summary>
- /// <param name="phrase">The phrase.</param>
- /// <returns>System.String.</returns>
- string GetLocalizedString(string phrase);
+ /// <summary>
+ /// Gets the localization options.
+ /// </summary>
+ /// <returns><see cref="IEnumerable{LocalizationOption}" />.</returns>
+ IEnumerable<LocalizationOption> GetLocalizationOptions();
- /// <summary>
- /// Gets the localization options.
- /// </summary>
- /// <returns><see cref="IEnumerable{LocalizationOption}" />.</returns>
- IEnumerable<LocalizationOption> GetLocalizationOptions();
+ /// <summary>
+ /// Returns the correct <see cref="CultureDto" /> for the given language.
+ /// </summary>
+ /// <param name="language">The language.</param>
+ /// <returns>The correct <see cref="CultureDto" /> for the given language.</returns>
+ CultureDto? FindLanguageInfo(string language);
- /// <summary>
- /// Returns the correct <see cref="CultureDto" /> for the given language.
- /// </summary>
- /// <param name="language">The language.</param>
- /// <returns>The correct <see cref="CultureDto" /> for the given language.</returns>
- CultureDto? FindLanguageInfo(string language);
- }
+ /// <summary>
+ /// Returns the language in ISO 639-2/T when the input is ISO 639-2/B.
+ /// </summary>
+ /// <param name="isoB">The language in ISO 639-2/B.</param>
+ /// <param name="isoT">The language in ISO 639-2/T.</param>
+ /// <returns>Whether the language could be converted.</returns>
+ public bool TryGetISO6392TFromB(string isoB, [NotNullWhen(true)] out string? isoT);
}
diff --git a/MediaBrowser.Model/IO/AsyncFile.cs b/MediaBrowser.Model/IO/AsyncFile.cs
index 3c8007d1c..a9db6b81c 100644
--- a/MediaBrowser.Model/IO/AsyncFile.cs
+++ b/MediaBrowser.Model/IO/AsyncFile.cs
@@ -27,6 +27,14 @@ namespace MediaBrowser.Model.IO
};
/// <summary>
+ /// Creates, or truncates and overwrites, a file in the specified path.
+ /// </summary>
+ /// <param name="path">The path and name of the file to create.</param>
+ /// <returns>A <see cref="FileStream" /> that provides read/write access to the file specified in path.</returns>
+ public static FileStream Create(string path)
+ => new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
+
+ /// <summary>
/// Opens an existing file for reading.
/// </summary>
/// <param name="path">The file to be opened for reading.</param>
diff --git a/MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs b/MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs
index b26f5f45f..1e8add943 100644
--- a/MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs
+++ b/MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs
@@ -83,7 +83,7 @@ namespace MediaBrowser.Model.LiveTv
/// Gets or sets the parent primary image item identifier.
/// </summary>
/// <value>The parent primary image item identifier.</value>
- public string ParentPrimaryImageItemId { get; set; }
+ public Guid? ParentPrimaryImageItemId { get; set; }
/// <summary>
/// Gets or sets the parent primary image tag.
diff --git a/MediaBrowser.Model/LiveTv/TunerHostInfo.cs b/MediaBrowser.Model/LiveTv/TunerHostInfo.cs
index a355387b1..b70333bce 100644
--- a/MediaBrowser.Model/LiveTv/TunerHostInfo.cs
+++ b/MediaBrowser.Model/LiveTv/TunerHostInfo.cs
@@ -9,6 +9,7 @@ namespace MediaBrowser.Model.LiveTv
{
AllowHWTranscoding = true;
IgnoreDts = true;
+ ReadAtNativeFramerate = false;
AllowStreamSharing = true;
AllowFmp4TranscodingContainer = false;
FallbackMaxStreamingBitrate = 30000000;
@@ -43,5 +44,7 @@ namespace MediaBrowser.Model.LiveTv
public string UserAgent { get; set; }
public bool IgnoreDts { get; set; }
+
+ public bool ReadAtNativeFramerate { get; set; }
}
}
diff --git a/MediaBrowser.Model/Lyrics/LyricLine.cs b/MediaBrowser.Model/Lyrics/LyricLine.cs
index 64d1f64c2..788bace69 100644
--- a/MediaBrowser.Model/Lyrics/LyricLine.cs
+++ b/MediaBrowser.Model/Lyrics/LyricLine.cs
@@ -1,3 +1,5 @@
+using System.Collections.Generic;
+
namespace MediaBrowser.Model.Lyrics;
/// <summary>
@@ -10,10 +12,12 @@ public class LyricLine
/// </summary>
/// <param name="text">The lyric text.</param>
/// <param name="start">The lyric start time in ticks.</param>
- public LyricLine(string text, long? start = null)
+ /// <param name="cues">The time-aligned cues for the song's lyrics.</param>
+ public LyricLine(string text, long? start = null, IReadOnlyList<LyricLineCue>? cues = null)
{
Text = text;
Start = start;
+ Cues = cues;
}
/// <summary>
@@ -25,4 +29,9 @@ public class LyricLine
/// Gets the start time in ticks.
/// </summary>
public long? Start { get; }
+
+ /// <summary>
+ /// Gets the time-aligned cues for the song's lyrics.
+ /// </summary>
+ public IReadOnlyList<LyricLineCue>? Cues { get; }
}
diff --git a/MediaBrowser.Model/Lyrics/LyricLineCue.cs b/MediaBrowser.Model/Lyrics/LyricLineCue.cs
new file mode 100644
index 000000000..1172a0231
--- /dev/null
+++ b/MediaBrowser.Model/Lyrics/LyricLineCue.cs
@@ -0,0 +1,35 @@
+namespace MediaBrowser.Model.Lyrics;
+
+/// <summary>
+/// LyricLineCue model, holds information about the timing of words within a LyricLine.
+/// </summary>
+public class LyricLineCue
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="LyricLineCue"/> class.
+ /// </summary>
+ /// <param name="position">The start of the character index of the lyric.</param>
+ /// <param name="start">The start of the timestamp the lyric is synced to in ticks.</param>
+ /// <param name="end">The end of the timestamp the lyric is synced to in ticks.</param>
+ public LyricLineCue(int position, long start, long? end)
+ {
+ Position = position;
+ Start = start;
+ End = end;
+ }
+
+ /// <summary>
+ /// Gets the character index of the lyric.
+ /// </summary>
+ public int Position { get; }
+
+ /// <summary>
+ /// Gets the timestamp the lyric is synced to in ticks.
+ /// </summary>
+ public long Start { get; }
+
+ /// <summary>
+ /// Gets the end timestamp the lyric is synced to in ticks.
+ /// </summary>
+ public long? End { get; }
+}
diff --git a/MediaBrowser.Model/Lyrics/LyricSearchRequest.cs b/MediaBrowser.Model/Lyrics/LyricSearchRequest.cs
index 48c442a55..67f3d7b42 100644
--- a/MediaBrowser.Model/Lyrics/LyricSearchRequest.cs
+++ b/MediaBrowser.Model/Lyrics/LyricSearchRequest.cs
@@ -15,7 +15,12 @@ public class LyricSearchRequest : IHasProviderIds
public string? MediaPath { get; set; }
/// <summary>
- /// Gets or sets the artist name.
+ /// Gets or sets the album artist names.
+ /// </summary>
+ public IReadOnlyList<string>? AlbumArtistsNames { get; set; }
+
+ /// <summary>
+ /// Gets or sets the artist names.
/// </summary>
public IReadOnlyList<string>? ArtistNames { get; set; }
diff --git a/MediaBrowser.Model/MediaInfo/AudioIndexSource.cs b/MediaBrowser.Model/MediaInfo/AudioIndexSource.cs
new file mode 100644
index 000000000..810087b92
--- /dev/null
+++ b/MediaBrowser.Model/MediaInfo/AudioIndexSource.cs
@@ -0,0 +1,30 @@
+using System;
+
+namespace MediaBrowser.Model.MediaInfo;
+
+/// <summary>
+/// How is the audio index determined.
+/// </summary>
+[Flags]
+public enum AudioIndexSource
+{
+ /// <summary>
+ /// The default index when no preference is specified.
+ /// </summary>
+ None = 0,
+
+ /// <summary>
+ /// The index is calculated whether the track is marked as default or not.
+ /// </summary>
+ Default = 1 << 0,
+
+ /// <summary>
+ /// The index is calculated whether the track is in preferred language or not.
+ /// </summary>
+ Language = 1 << 1,
+
+ /// <summary>
+ /// The index is specified by the user.
+ /// </summary>
+ User = 1 << 2
+}
diff --git a/MediaBrowser.Model/MediaSegments/MediaSegmentDto.cs b/MediaBrowser.Model/MediaSegments/MediaSegmentDto.cs
index 6e5c7885c..d9129c395 100644
--- a/MediaBrowser.Model/MediaSegments/MediaSegmentDto.cs
+++ b/MediaBrowser.Model/MediaSegments/MediaSegmentDto.cs
@@ -1,4 +1,5 @@
using System;
+using System.ComponentModel;
using Jellyfin.Database.Implementations.Enums;
namespace MediaBrowser.Model.MediaSegments;
@@ -21,6 +22,7 @@ public class MediaSegmentDto
/// <summary>
/// Gets or sets the type of content this segment defines.
/// </summary>
+ [DefaultValue(MediaSegmentType.Unknown)]
public MediaSegmentType Type { get; set; }
/// <summary>
diff --git a/MediaBrowser.Model/Querying/ItemFields.cs b/MediaBrowser.Model/Querying/ItemFields.cs
index 49d7c0bcb..ffecd392f 100644
--- a/MediaBrowser.Model/Querying/ItemFields.cs
+++ b/MediaBrowser.Model/Querying/ItemFields.cs
@@ -1,7 +1,3 @@
-#pragma warning disable CS1591
-
-using System;
-
namespace MediaBrowser.Model.Querying
{
/// <summary>
@@ -39,6 +35,9 @@ namespace MediaBrowser.Model.Querying
/// </summary>
Trickplay,
+ /// <summary>
+ /// The child count.
+ /// </summary>
ChildCount,
/// <summary>
@@ -82,11 +81,6 @@ namespace MediaBrowser.Model.Querying
Genres,
/// <summary>
- /// The home page URL.
- /// </summary>
- HomePageUrl,
-
- /// <summary>
/// The item counts.
/// </summary>
ItemCounts,
@@ -101,6 +95,9 @@ namespace MediaBrowser.Model.Querying
/// </summary>
MediaSources,
+ /// <summary>
+ /// The original title.
+ /// </summary>
OriginalTitle,
/// <summary>
@@ -123,6 +120,9 @@ namespace MediaBrowser.Model.Querying
/// </summary>
People,
+ /// <summary>
+ /// Value indicating whether playback access is granted.
+ /// </summary>
PlayAccess,
/// <summary>
@@ -140,6 +140,9 @@ namespace MediaBrowser.Model.Querying
/// </summary>
PrimaryImageAspectRatio,
+ /// <summary>
+ /// The recursive item count.
+ /// </summary>
RecursiveItemCount,
/// <summary>
@@ -148,14 +151,6 @@ namespace MediaBrowser.Model.Querying
Settings,
/// <summary>
- /// The screenshot image tags.
- /// </summary>
- [Obsolete("Screenshot image type is no longer used.")]
- ScreenshotImageTags,
-
- SeriesPrimaryImage,
-
- /// <summary>
/// The series studio.
/// </summary>
SeriesStudio,
@@ -201,26 +196,58 @@ namespace MediaBrowser.Model.Querying
SeasonUserData,
/// <summary>
- /// The service name.
+ /// The last time metadata was refreshed.
/// </summary>
- ServiceName,
- ThemeSongIds,
- ThemeVideoIds,
- ExternalEtag,
- PresentationUniqueKey,
- InheritedParentalRatingValue,
- ExternalSeriesId,
- SeriesPresentationUniqueKey,
DateLastRefreshed,
+
+ /// <summary>
+ /// The last time metadata was saved.
+ /// </summary>
DateLastSaved,
+
+ /// <summary>
+ /// The refresh state.
+ /// </summary>
RefreshState,
+
+ /// <summary>
+ /// The channel image.
+ /// </summary>
ChannelImage,
+
+ /// <summary>
+ /// Value indicating whether media source display is enabled.
+ /// </summary>
EnableMediaSourceDisplay,
+
+ /// <summary>
+ /// The width.
+ /// </summary>
Width,
+
+ /// <summary>
+ /// The height.
+ /// </summary>
Height,
+
+ /// <summary>
+ /// The external Ids.
+ /// </summary>
ExtraIds,
+
+ /// <summary>
+ /// The local trailer count.
+ /// </summary>
LocalTrailerCount,
+
+ /// <summary>
+ /// Value indicating whether the item is HD.
+ /// </summary>
IsHD,
+
+ /// <summary>
+ /// The special feature count.
+ /// </summary>
SpecialFeatureCount
}
}
diff --git a/MediaBrowser.Model/Search/SearchHint.cs b/MediaBrowser.Model/Search/SearchHint.cs
index 2e2979fcf..a18a813cc 100644
--- a/MediaBrowser.Model/Search/SearchHint.cs
+++ b/MediaBrowser.Model/Search/SearchHint.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.ComponentModel;
using Jellyfin.Data.Enums;
namespace MediaBrowser.Model.Search
@@ -115,6 +116,7 @@ namespace MediaBrowser.Model.Search
/// Gets or sets the type of the media.
/// </summary>
/// <value>The type of the media.</value>
+ [DefaultValue(MediaType.Unknown)]
public MediaType MediaType { get; set; }
/// <summary>
diff --git a/MediaBrowser.Model/SyncPlay/GroupUpdate.cs b/MediaBrowser.Model/SyncPlay/GroupUpdate.cs
index ec67d7ea8..794443499 100644
--- a/MediaBrowser.Model/SyncPlay/GroupUpdate.cs
+++ b/MediaBrowser.Model/SyncPlay/GroupUpdate.cs
@@ -5,15 +5,18 @@ namespace MediaBrowser.Model.SyncPlay;
/// <summary>
/// Group update without data.
/// </summary>
-public abstract class GroupUpdate
+/// <typeparam name="T">The type of the update data.</typeparam>
+public abstract class GroupUpdate<T>
{
/// <summary>
- /// Initializes a new instance of the <see cref="GroupUpdate"/> class.
+ /// Initializes a new instance of the <see cref="GroupUpdate{T}"/> class.
/// </summary>
/// <param name="groupId">The group identifier.</param>
- protected GroupUpdate(Guid groupId)
+ /// <param name="data">The update data.</param>
+ protected GroupUpdate(Guid groupId, T data)
{
GroupId = groupId;
+ Data = data;
}
/// <summary>
@@ -23,8 +26,14 @@ public abstract class GroupUpdate
public Guid GroupId { get; }
/// <summary>
+ /// Gets the update data.
+ /// </summary>
+ /// <value>The update data.</value>
+ public T Data { get; }
+
+ /// <summary>
/// Gets the update type.
/// </summary>
/// <value>The update type.</value>
- public GroupUpdateType Type { get; init; }
+ public abstract GroupUpdateType Type { get; }
}
diff --git a/MediaBrowser.Model/SyncPlay/GroupUpdateOfT.cs b/MediaBrowser.Model/SyncPlay/GroupUpdateOfT.cs
deleted file mode 100644
index 25cd44461..000000000
--- a/MediaBrowser.Model/SyncPlay/GroupUpdateOfT.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-#pragma warning disable SA1649
-
-using System;
-
-namespace MediaBrowser.Model.SyncPlay;
-
-/// <summary>
-/// Class GroupUpdate.
-/// </summary>
-/// <typeparam name="T">The type of the data of the message.</typeparam>
-public class GroupUpdate<T> : GroupUpdate
-{
- /// <summary>
- /// Initializes a new instance of the <see cref="GroupUpdate{T}"/> class.
- /// </summary>
- /// <param name="groupId">The group identifier.</param>
- /// <param name="type">The update type.</param>
- /// <param name="data">The update data.</param>
- public GroupUpdate(Guid groupId, GroupUpdateType type, T data)
- : base(groupId)
- {
- Data = data;
- Type = type;
- }
-
- /// <summary>
- /// Gets the update data.
- /// </summary>
- /// <value>The update data.</value>
- public T Data { get; }
-}
diff --git a/MediaBrowser.Model/SyncPlay/GroupUpdateType.cs b/MediaBrowser.Model/SyncPlay/GroupUpdateType.cs
index 907d1defe..e792229a4 100644
--- a/MediaBrowser.Model/SyncPlay/GroupUpdateType.cs
+++ b/MediaBrowser.Model/SyncPlay/GroupUpdateType.cs
@@ -46,16 +46,6 @@ namespace MediaBrowser.Model.SyncPlay
GroupDoesNotExist,
/// <summary>
- /// The create-group-denied error. Sent when a user tries to create a group without required permissions.
- /// </summary>
- CreateGroupDenied,
-
- /// <summary>
- /// The join-group-denied error. Sent when a user tries to join a group without required permissions.
- /// </summary>
- JoinGroupDenied,
-
- /// <summary>
/// The library-access-denied error. Sent when a user tries to join a group without required access to the library.
/// </summary>
LibraryAccessDenied
diff --git a/MediaBrowser.Model/SyncPlay/SyncPlayGroupDoesNotExistUpdate.cs b/MediaBrowser.Model/SyncPlay/SyncPlayGroupDoesNotExistUpdate.cs
new file mode 100644
index 000000000..7e2d10c8b
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/SyncPlayGroupDoesNotExistUpdate.cs
@@ -0,0 +1,21 @@
+using System;
+using System.ComponentModel;
+
+namespace MediaBrowser.Model.SyncPlay;
+
+/// <inheritdoc />
+public class SyncPlayGroupDoesNotExistUpdate : GroupUpdate<string>
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SyncPlayGroupDoesNotExistUpdate"/> class.
+ /// </summary>
+ /// <param name="groupId">The groupId.</param>
+ /// <param name="data">The data.</param>
+ public SyncPlayGroupDoesNotExistUpdate(Guid groupId, string data) : base(groupId, data)
+ {
+ }
+
+ /// <inheritdoc />
+ [DefaultValue(GroupUpdateType.GroupDoesNotExist)]
+ public override GroupUpdateType Type => GroupUpdateType.GroupDoesNotExist;
+}
diff --git a/MediaBrowser.Model/SyncPlay/SyncPlayGroupJoinedUpdate.cs b/MediaBrowser.Model/SyncPlay/SyncPlayGroupJoinedUpdate.cs
new file mode 100644
index 000000000..bfb49152a
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/SyncPlayGroupJoinedUpdate.cs
@@ -0,0 +1,21 @@
+using System;
+using System.ComponentModel;
+
+namespace MediaBrowser.Model.SyncPlay;
+
+/// <inheritdoc />
+public class SyncPlayGroupJoinedUpdate : GroupUpdate<GroupInfoDto>
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SyncPlayGroupJoinedUpdate"/> class.
+ /// </summary>
+ /// <param name="groupId">The groupId.</param>
+ /// <param name="data">The data.</param>
+ public SyncPlayGroupJoinedUpdate(Guid groupId, GroupInfoDto data) : base(groupId, data)
+ {
+ }
+
+ /// <inheritdoc />
+ [DefaultValue(GroupUpdateType.GroupJoined)]
+ public override GroupUpdateType Type => GroupUpdateType.GroupJoined;
+}
diff --git a/MediaBrowser.Model/SyncPlay/SyncPlayGroupLeftUpdate.cs b/MediaBrowser.Model/SyncPlay/SyncPlayGroupLeftUpdate.cs
new file mode 100644
index 000000000..5ff60c5c2
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/SyncPlayGroupLeftUpdate.cs
@@ -0,0 +1,21 @@
+using System;
+using System.ComponentModel;
+
+namespace MediaBrowser.Model.SyncPlay;
+
+/// <inheritdoc />
+public class SyncPlayGroupLeftUpdate : GroupUpdate<string>
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SyncPlayGroupLeftUpdate"/> class.
+ /// </summary>
+ /// <param name="groupId">The groupId.</param>
+ /// <param name="data">The data.</param>
+ public SyncPlayGroupLeftUpdate(Guid groupId, string data) : base(groupId, data)
+ {
+ }
+
+ /// <inheritdoc />
+ [DefaultValue(GroupUpdateType.GroupLeft)]
+ public override GroupUpdateType Type => GroupUpdateType.GroupLeft;
+}
diff --git a/MediaBrowser.Model/SyncPlay/SyncPlayLibraryAccessDeniedUpdate.cs b/MediaBrowser.Model/SyncPlay/SyncPlayLibraryAccessDeniedUpdate.cs
new file mode 100644
index 000000000..0d9a722f7
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/SyncPlayLibraryAccessDeniedUpdate.cs
@@ -0,0 +1,21 @@
+using System;
+using System.ComponentModel;
+
+namespace MediaBrowser.Model.SyncPlay;
+
+/// <inheritdoc />
+public class SyncPlayLibraryAccessDeniedUpdate : GroupUpdate<string>
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SyncPlayLibraryAccessDeniedUpdate"/> class.
+ /// </summary>
+ /// <param name="groupId">The groupId.</param>
+ /// <param name="data">The data.</param>
+ public SyncPlayLibraryAccessDeniedUpdate(Guid groupId, string data) : base(groupId, data)
+ {
+ }
+
+ /// <inheritdoc />
+ [DefaultValue(GroupUpdateType.LibraryAccessDenied)]
+ public override GroupUpdateType Type => GroupUpdateType.LibraryAccessDenied;
+}
diff --git a/MediaBrowser.Model/SyncPlay/SyncPlayNotInGroupUpdate.cs b/MediaBrowser.Model/SyncPlay/SyncPlayNotInGroupUpdate.cs
new file mode 100644
index 000000000..a3b610f61
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/SyncPlayNotInGroupUpdate.cs
@@ -0,0 +1,21 @@
+using System;
+using System.ComponentModel;
+
+namespace MediaBrowser.Model.SyncPlay;
+
+/// <inheritdoc />
+public class SyncPlayNotInGroupUpdate : GroupUpdate<string>
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SyncPlayNotInGroupUpdate"/> class.
+ /// </summary>
+ /// <param name="groupId">The groupId.</param>
+ /// <param name="data">The data.</param>
+ public SyncPlayNotInGroupUpdate(Guid groupId, string data) : base(groupId, data)
+ {
+ }
+
+ /// <inheritdoc />
+ [DefaultValue(GroupUpdateType.NotInGroup)]
+ public override GroupUpdateType Type => GroupUpdateType.NotInGroup;
+}
diff --git a/MediaBrowser.Model/SyncPlay/SyncPlayPlayQueueUpdate.cs b/MediaBrowser.Model/SyncPlay/SyncPlayPlayQueueUpdate.cs
new file mode 100644
index 000000000..83d9bd40b
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/SyncPlayPlayQueueUpdate.cs
@@ -0,0 +1,21 @@
+using System;
+using System.ComponentModel;
+
+namespace MediaBrowser.Model.SyncPlay;
+
+/// <inheritdoc />
+public class SyncPlayPlayQueueUpdate : GroupUpdate<PlayQueueUpdate>
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SyncPlayPlayQueueUpdate"/> class.
+ /// </summary>
+ /// <param name="groupId">The groupId.</param>
+ /// <param name="data">The data.</param>
+ public SyncPlayPlayQueueUpdate(Guid groupId, PlayQueueUpdate data) : base(groupId, data)
+ {
+ }
+
+ /// <inheritdoc />
+ [DefaultValue(GroupUpdateType.PlayQueue)]
+ public override GroupUpdateType Type => GroupUpdateType.PlayQueue;
+}
diff --git a/MediaBrowser.Model/SyncPlay/SyncPlayStateUpdate.cs b/MediaBrowser.Model/SyncPlay/SyncPlayStateUpdate.cs
new file mode 100644
index 000000000..744ca46a0
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/SyncPlayStateUpdate.cs
@@ -0,0 +1,21 @@
+using System;
+using System.ComponentModel;
+
+namespace MediaBrowser.Model.SyncPlay;
+
+/// <inheritdoc />
+public class SyncPlayStateUpdate : GroupUpdate<GroupStateUpdate>
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SyncPlayStateUpdate"/> class.
+ /// </summary>
+ /// <param name="groupId">The groupId.</param>
+ /// <param name="data">The data.</param>
+ public SyncPlayStateUpdate(Guid groupId, GroupStateUpdate data) : base(groupId, data)
+ {
+ }
+
+ /// <inheritdoc />
+ [DefaultValue(GroupUpdateType.StateUpdate)]
+ public override GroupUpdateType Type => GroupUpdateType.StateUpdate;
+}
diff --git a/MediaBrowser.Model/SyncPlay/SyncPlayUserJoinedUpdate.cs b/MediaBrowser.Model/SyncPlay/SyncPlayUserJoinedUpdate.cs
new file mode 100644
index 000000000..e8c6b4df4
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/SyncPlayUserJoinedUpdate.cs
@@ -0,0 +1,21 @@
+using System;
+using System.ComponentModel;
+
+namespace MediaBrowser.Model.SyncPlay;
+
+/// <inheritdoc />
+public class SyncPlayUserJoinedUpdate : GroupUpdate<string>
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SyncPlayUserJoinedUpdate"/> class.
+ /// </summary>
+ /// <param name="groupId">The groupId.</param>
+ /// <param name="data">The data.</param>
+ public SyncPlayUserJoinedUpdate(Guid groupId, string data) : base(groupId, data)
+ {
+ }
+
+ /// <inheritdoc />
+ [DefaultValue(GroupUpdateType.UserJoined)]
+ public override GroupUpdateType Type => GroupUpdateType.UserJoined;
+}
diff --git a/MediaBrowser.Model/SyncPlay/SyncPlayUserLeftUpdate.cs b/MediaBrowser.Model/SyncPlay/SyncPlayUserLeftUpdate.cs
new file mode 100644
index 000000000..97be8e63a
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/SyncPlayUserLeftUpdate.cs
@@ -0,0 +1,21 @@
+using System;
+using System.ComponentModel;
+
+namespace MediaBrowser.Model.SyncPlay;
+
+/// <inheritdoc />
+public class SyncPlayUserLeftUpdate : GroupUpdate<string>
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SyncPlayUserLeftUpdate"/> class.
+ /// </summary>
+ /// <param name="groupId">The groupId.</param>
+ /// <param name="data">The data.</param>
+ public SyncPlayUserLeftUpdate(Guid groupId, string data) : base(groupId, data)
+ {
+ }
+
+ /// <inheritdoc />
+ [DefaultValue(GroupUpdateType.UserLeft)]
+ public override GroupUpdateType Type => GroupUpdateType.UserLeft;
+}
diff --git a/MediaBrowser.Model/System/FolderStorageInfo.cs b/MediaBrowser.Model/System/FolderStorageInfo.cs
new file mode 100644
index 000000000..7b10e4ea5
--- /dev/null
+++ b/MediaBrowser.Model/System/FolderStorageInfo.cs
@@ -0,0 +1,32 @@
+namespace MediaBrowser.Model.System;
+
+/// <summary>
+/// Contains information about a specific folder.
+/// </summary>
+public record FolderStorageInfo
+{
+ /// <summary>
+ /// Gets the path of the folder in question.
+ /// </summary>
+ public required string Path { get; init; }
+
+ /// <summary>
+ /// Gets the free space of the underlying storage device of the <see cref="Path"/>.
+ /// </summary>
+ public long FreeSpace { get; init; }
+
+ /// <summary>
+ /// Gets the used space of the underlying storage device of the <see cref="Path"/>.
+ /// </summary>
+ public long UsedSpace { get; init; }
+
+ /// <summary>
+ /// Gets the kind of storage device of the <see cref="Path"/>.
+ /// </summary>
+ public string? StorageType { get; init; }
+
+ /// <summary>
+ /// Gets the Device Identifier.
+ /// </summary>
+ public string? DeviceId { get; init; }
+}
diff --git a/MediaBrowser.Model/System/LibraryStorageInfo.cs b/MediaBrowser.Model/System/LibraryStorageInfo.cs
new file mode 100644
index 000000000..d4111b29c
--- /dev/null
+++ b/MediaBrowser.Model/System/LibraryStorageInfo.cs
@@ -0,0 +1,25 @@
+using System;
+using System.Collections.Generic;
+
+namespace MediaBrowser.Model.System;
+
+/// <summary>
+/// Contains informations about a libraries storage informations.
+/// </summary>
+public class LibraryStorageInfo
+{
+ /// <summary>
+ /// Gets or sets the Library Id.
+ /// </summary>
+ public required Guid Id { get; set; }
+
+ /// <summary>
+ /// Gets or sets the name of the library.
+ /// </summary>
+ public required string Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the storage informations about the folders used in a library.
+ /// </summary>
+ public required IReadOnlyCollection<FolderStorageInfo> Folders { get; set; }
+}
diff --git a/MediaBrowser.Model/System/SystemInfo.cs b/MediaBrowser.Model/System/SystemInfo.cs
index f37ac6a14..232a2a6bc 100644
--- a/MediaBrowser.Model/System/SystemInfo.cs
+++ b/MediaBrowser.Model/System/SystemInfo.cs
@@ -6,133 +6,139 @@ using System.Collections.Generic;
using System.ComponentModel;
using MediaBrowser.Model.Updates;
-namespace MediaBrowser.Model.System
+namespace MediaBrowser.Model.System;
+
+/// <summary>
+/// Class SystemInfo.
+/// </summary>
+public class SystemInfo : PublicSystemInfo
{
/// <summary>
- /// Class SystemInfo.
+ /// Initializes a new instance of the <see cref="SystemInfo" /> class.
/// </summary>
- public class SystemInfo : PublicSystemInfo
+ public SystemInfo()
{
- /// <summary>
- /// Initializes a new instance of the <see cref="SystemInfo" /> class.
- /// </summary>
- public SystemInfo()
- {
- CompletedInstallations = Array.Empty<InstallationInfo>();
- }
-
- /// <summary>
- /// Gets or sets the display name of the operating system.
- /// </summary>
- /// <value>The display name of the operating system.</value>
- [Obsolete("This is no longer set")]
- public string OperatingSystemDisplayName { get; set; } = string.Empty;
-
- /// <summary>
- /// Gets or sets the package name.
- /// </summary>
- /// <value>The value of the '-package' command line argument.</value>
- public string PackageName { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance has pending restart.
- /// </summary>
- /// <value><c>true</c> if this instance has pending restart; otherwise, <c>false</c>.</value>
- public bool HasPendingRestart { get; set; }
-
- public bool IsShuttingDown { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether [supports library monitor].
- /// </summary>
- /// <value><c>true</c> if [supports library monitor]; otherwise, <c>false</c>.</value>
- public bool SupportsLibraryMonitor { get; set; }
-
- /// <summary>
- /// Gets or sets the web socket port number.
- /// </summary>
- /// <value>The web socket port number.</value>
- public int WebSocketPortNumber { get; set; }
-
- /// <summary>
- /// Gets or sets the completed installations.
- /// </summary>
- /// <value>The completed installations.</value>
- public InstallationInfo[] CompletedInstallations { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance can self restart.
- /// </summary>
- /// <value><c>true</c>.</value>
- [Obsolete("This is always true")]
- [DefaultValue(true)]
- public bool CanSelfRestart { get; set; } = true;
-
- [Obsolete("This is always false")]
- [DefaultValue(false)]
- public bool CanLaunchWebBrowser { get; set; } = false;
-
- /// <summary>
- /// Gets or sets the program data path.
- /// </summary>
- /// <value>The program data path.</value>
- public string ProgramDataPath { get; set; }
-
- /// <summary>
- /// Gets or sets the web UI resources path.
- /// </summary>
- /// <value>The web UI resources path.</value>
- public string WebPath { get; set; }
-
- /// <summary>
- /// Gets or sets the items by name path.
- /// </summary>
- /// <value>The items by name path.</value>
- public string ItemsByNamePath { get; set; }
-
- /// <summary>
- /// Gets or sets the cache path.
- /// </summary>
- /// <value>The cache path.</value>
- public string CachePath { get; set; }
-
- /// <summary>
- /// Gets or sets the log path.
- /// </summary>
- /// <value>The log path.</value>
- public string LogPath { get; set; }
-
- /// <summary>
- /// Gets or sets the internal metadata path.
- /// </summary>
- /// <value>The internal metadata path.</value>
- public string InternalMetadataPath { get; set; }
-
- /// <summary>
- /// Gets or sets the transcode path.
- /// </summary>
- /// <value>The transcode path.</value>
- public string TranscodingTempPath { get; set; }
-
- /// <summary>
- /// Gets or sets the list of cast receiver applications.
- /// </summary>
- public IReadOnlyList<CastReceiverApplication> CastReceiverApplications { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this instance has update available.
- /// </summary>
- /// <value><c>true</c> if this instance has update available; otherwise, <c>false</c>.</value>
- [Obsolete("This should be handled by the package manager")]
- [DefaultValue(false)]
- public bool HasUpdateAvailable { get; set; }
-
- [Obsolete("This isn't set correctly anymore")]
- [DefaultValue("System")]
- public string EncoderLocation { get; set; } = "System";
-
- [Obsolete("This is no longer set")]
- [DefaultValue("X64")]
- public string SystemArchitecture { get; set; } = "X64";
+ CompletedInstallations = Array.Empty<InstallationInfo>();
}
+
+ /// <summary>
+ /// Gets or sets the display name of the operating system.
+ /// </summary>
+ /// <value>The display name of the operating system.</value>
+ [Obsolete("This is no longer set")]
+ public string OperatingSystemDisplayName { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the package name.
+ /// </summary>
+ /// <value>The value of the '-package' command line argument.</value>
+ public string PackageName { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance has pending restart.
+ /// </summary>
+ /// <value><c>true</c> if this instance has pending restart; otherwise, <c>false</c>.</value>
+ public bool HasPendingRestart { get; set; }
+
+ public bool IsShuttingDown { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether [supports library monitor].
+ /// </summary>
+ /// <value><c>true</c> if [supports library monitor]; otherwise, <c>false</c>.</value>
+ public bool SupportsLibraryMonitor { get; set; }
+
+ /// <summary>
+ /// Gets or sets the web socket port number.
+ /// </summary>
+ /// <value>The web socket port number.</value>
+ public int WebSocketPortNumber { get; set; }
+
+ /// <summary>
+ /// Gets or sets the completed installations.
+ /// </summary>
+ /// <value>The completed installations.</value>
+ public InstallationInfo[] CompletedInstallations { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance can self restart.
+ /// </summary>
+ /// <value><c>true</c>.</value>
+ [Obsolete("This is always true")]
+ [DefaultValue(true)]
+ public bool CanSelfRestart { get; set; } = true;
+
+ [Obsolete("This is always false")]
+ [DefaultValue(false)]
+ public bool CanLaunchWebBrowser { get; set; } = false;
+
+ /// <summary>
+ /// Gets or sets the program data path.
+ /// </summary>
+ /// <value>The program data path.</value>
+ [Obsolete("Use the newer SystemStorageDto instead")]
+ public string ProgramDataPath { get; set; }
+
+ /// <summary>
+ /// Gets or sets the web UI resources path.
+ /// </summary>
+ /// <value>The web UI resources path.</value>
+ [Obsolete("Use the newer SystemStorageDto instead")]
+ public string WebPath { get; set; }
+
+ /// <summary>
+ /// Gets or sets the items by name path.
+ /// </summary>
+ /// <value>The items by name path.</value>
+ [Obsolete("Use the newer SystemStorageDto instead")]
+ public string ItemsByNamePath { get; set; }
+
+ /// <summary>
+ /// Gets or sets the cache path.
+ /// </summary>
+ /// <value>The cache path.</value>
+ [Obsolete("Use the newer SystemStorageDto instead")]
+ public string CachePath { get; set; }
+
+ /// <summary>
+ /// Gets or sets the log path.
+ /// </summary>
+ /// <value>The log path.</value>
+ [Obsolete("Use the newer SystemStorageDto instead")]
+ public string LogPath { get; set; }
+
+ /// <summary>
+ /// Gets or sets the internal metadata path.
+ /// </summary>
+ /// <value>The internal metadata path.</value>
+ [Obsolete("Use the newer SystemStorageDto instead")]
+ public string InternalMetadataPath { get; set; }
+
+ /// <summary>
+ /// Gets or sets the transcode path.
+ /// </summary>
+ /// <value>The transcode path.</value>
+ [Obsolete("Use the newer SystemStorageDto instead")]
+ public string TranscodingTempPath { get; set; }
+
+ /// <summary>
+ /// Gets or sets the list of cast receiver applications.
+ /// </summary>
+ public IReadOnlyList<CastReceiverApplication> CastReceiverApplications { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance has update available.
+ /// </summary>
+ /// <value><c>true</c> if this instance has update available; otherwise, <c>false</c>.</value>
+ [Obsolete("This should be handled by the package manager")]
+ [DefaultValue(false)]
+ public bool HasUpdateAvailable { get; set; }
+
+ [Obsolete("This isn't set correctly anymore")]
+ [DefaultValue("System")]
+ public string EncoderLocation { get; set; } = "System";
+
+ [Obsolete("This is no longer set")]
+ [DefaultValue("X64")]
+ public string SystemArchitecture { get; set; } = "X64";
}
diff --git a/MediaBrowser.Model/System/SystemStorageInfo.cs b/MediaBrowser.Model/System/SystemStorageInfo.cs
new file mode 100644
index 000000000..42e7a37e0
--- /dev/null
+++ b/MediaBrowser.Model/System/SystemStorageInfo.cs
@@ -0,0 +1,56 @@
+using System.Collections.Generic;
+
+namespace MediaBrowser.Model.System;
+
+/// <summary>
+/// Contains informations about the systems storage.
+/// </summary>
+public class SystemStorageInfo
+{
+ /// <summary>
+ /// Gets or sets the program data path.
+ /// </summary>
+ /// <value>The program data path.</value>
+ public required FolderStorageInfo ProgramDataFolder { get; set; }
+
+ /// <summary>
+ /// Gets or sets the web UI resources path.
+ /// </summary>
+ /// <value>The web UI resources path.</value>
+ public required FolderStorageInfo WebFolder { get; set; }
+
+ /// <summary>
+ /// Gets or sets the items by name path.
+ /// </summary>
+ /// <value>The items by name path.</value>
+ public required FolderStorageInfo ImageCacheFolder { get; set; }
+
+ /// <summary>
+ /// Gets or sets the cache path.
+ /// </summary>
+ /// <value>The cache path.</value>
+ public required FolderStorageInfo CacheFolder { get; set; }
+
+ /// <summary>
+ /// Gets or sets the log path.
+ /// </summary>
+ /// <value>The log path.</value>
+ public required FolderStorageInfo LogFolder { get; set; }
+
+ /// <summary>
+ /// Gets or sets the internal metadata path.
+ /// </summary>
+ /// <value>The internal metadata path.</value>
+ public required FolderStorageInfo InternalMetadataFolder { get; set; }
+
+ /// <summary>
+ /// Gets or sets the transcode path.
+ /// </summary>
+ /// <value>The transcode path.</value>
+ public required FolderStorageInfo TranscodingTempFolder { get; set; }
+
+ /// <summary>
+ /// Gets or sets the storage informations of all libraries.
+ /// </summary>
+ public required IReadOnlyCollection<LibraryStorageInfo> Libraries { get; set; }
+}
diff --git a/MediaBrowser.Model/Users/UserPolicy.cs b/MediaBrowser.Model/Users/UserPolicy.cs
index 3d430e101..2c393ca86 100644
--- a/MediaBrowser.Model/Users/UserPolicy.cs
+++ b/MediaBrowser.Model/Users/UserPolicy.cs
@@ -111,6 +111,8 @@ namespace MediaBrowser.Model.Users
/// <value>The max parental rating.</value>
public int? MaxParentalRating { get; set; }
+ public int? MaxParentalSubRating { get; set; }
+
public string[] BlockedTags { get; set; }
public string[] AllowedTags { get; set; }
diff --git a/MediaBrowser.Providers/Books/AudioBookMetadataService.cs b/MediaBrowser.Providers/Books/AudioBookMetadataService.cs
index 96e1165b6..1b2deaef3 100644
--- a/MediaBrowser.Providers/Books/AudioBookMetadataService.cs
+++ b/MediaBrowser.Providers/Books/AudioBookMetadataService.cs
@@ -1,7 +1,6 @@
-#pragma warning disable CS1591
-
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
@@ -9,42 +8,54 @@ using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Books
+namespace MediaBrowser.Providers.Books;
+
+/// <summary>
+/// Service to manage audiobook metadata.
+/// </summary>
+public class AudioBookMetadataService : MetadataService<AudioBook, SongInfo>
{
- public class AudioBookMetadataService : MetadataService<AudioBook, SongInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AudioBookMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public AudioBookMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<AudioBookMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public AudioBookMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<AudioBookMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
+ }
- /// <inheritdoc />
- protected override void MergeData(
- MetadataResult<AudioBook> source,
- MetadataResult<AudioBook> target,
- MetadataField[] lockedFields,
- bool replaceData,
- bool mergeMetadataSettings)
- {
- base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
+ /// <inheritdoc />
+ protected override void MergeData(
+ MetadataResult<AudioBook> source,
+ MetadataResult<AudioBook> target,
+ MetadataField[] lockedFields,
+ bool replaceData,
+ bool mergeMetadataSettings)
+ {
+ base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
- var sourceItem = source.Item;
- var targetItem = target.Item;
+ var sourceItem = source.Item;
+ var targetItem = target.Item;
- if (replaceData || targetItem.Artists.Count == 0)
- {
- targetItem.Artists = sourceItem.Artists;
- }
+ if (replaceData || targetItem.Artists.Count == 0)
+ {
+ targetItem.Artists = sourceItem.Artists;
+ }
- if (replaceData || string.IsNullOrEmpty(targetItem.Album))
- {
- targetItem.Album = sourceItem.Album;
- }
+ if (replaceData || string.IsNullOrEmpty(targetItem.Album))
+ {
+ targetItem.Album = sourceItem.Album;
}
}
}
diff --git a/MediaBrowser.Providers/Books/BookMetadataService.cs b/MediaBrowser.Providers/Books/BookMetadataService.cs
index 50b9922c6..97cd04b45 100644
--- a/MediaBrowser.Providers/Books/BookMetadataService.cs
+++ b/MediaBrowser.Providers/Books/BookMetadataService.cs
@@ -1,7 +1,6 @@
-#pragma warning disable CS1591
-
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
@@ -9,29 +8,41 @@ using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Books
+namespace MediaBrowser.Providers.Books;
+
+/// <summary>
+/// Service to manage book metadata.
+/// </summary>
+public class BookMetadataService : MetadataService<Book, BookInfo>
{
- public class BookMetadataService : MetadataService<Book, BookInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BookMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public BookMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<BookMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public BookMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<BookMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
+ }
- /// <inheritdoc />
- protected override void MergeData(MetadataResult<Book> source, MetadataResult<Book> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
- {
- base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Book> source, MetadataResult<Book> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ {
+ base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
- if (replaceData || string.IsNullOrEmpty(target.Item.SeriesName))
- {
- target.Item.SeriesName = source.Item.SeriesName;
- }
+ if (replaceData || string.IsNullOrEmpty(target.Item.SeriesName))
+ {
+ target.Item.SeriesName = source.Item.SeriesName;
}
}
}
diff --git a/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs b/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs
index b51ab4c08..ab3cd9483 100644
--- a/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs
+++ b/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs
@@ -1,10 +1,9 @@
-#pragma warning disable CS1591
-
using System.Collections.Generic;
using System.Linq;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
@@ -12,74 +11,86 @@ using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.BoxSets
+namespace MediaBrowser.Providers.BoxSets;
+
+/// <summary>
+/// Service to manage boxset metadata.
+/// </summary>
+public class BoxSetMetadataService : MetadataService<BoxSet, BoxSetInfo>
{
- public class BoxSetMetadataService : MetadataService<BoxSet, BoxSetInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BoxSetMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public BoxSetMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<BoxSetMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public BoxSetMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<BoxSetMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
+ }
- /// <inheritdoc />
- protected override bool EnableUpdatingGenresFromChildren => true;
+ /// <inheritdoc />
+ protected override bool EnableUpdatingGenresFromChildren => true;
- /// <inheritdoc />
- protected override bool EnableUpdatingOfficialRatingFromChildren => true;
+ /// <inheritdoc />
+ protected override bool EnableUpdatingOfficialRatingFromChildren => true;
- /// <inheritdoc />
- protected override bool EnableUpdatingStudiosFromChildren => true;
+ /// <inheritdoc />
+ protected override bool EnableUpdatingStudiosFromChildren => true;
- /// <inheritdoc />
- protected override bool EnableUpdatingPremiereDateFromChildren => true;
+ /// <inheritdoc />
+ protected override bool EnableUpdatingPremiereDateFromChildren => true;
- /// <inheritdoc />
- protected override IReadOnlyList<BaseItem> GetChildrenForMetadataUpdates(BoxSet item)
- {
- return item.GetLinkedChildren();
- }
+ /// <inheritdoc />
+ protected override IReadOnlyList<BaseItem> GetChildrenForMetadataUpdates(BoxSet item)
+ {
+ return item.GetLinkedChildren();
+ }
- /// <inheritdoc />
- protected override void MergeData(MetadataResult<BoxSet> source, MetadataResult<BoxSet> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
- {
- base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<BoxSet> source, MetadataResult<BoxSet> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ {
+ base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
- var sourceItem = source.Item;
- var targetItem = target.Item;
+ var sourceItem = source.Item;
+ var targetItem = target.Item;
- if (mergeMetadataSettings)
+ if (mergeMetadataSettings)
+ {
+ if (replaceData || targetItem.LinkedChildren.Length == 0)
+ {
+ targetItem.LinkedChildren = sourceItem.LinkedChildren;
+ }
+ else
{
- if (replaceData || targetItem.LinkedChildren.Length == 0)
- {
- targetItem.LinkedChildren = sourceItem.LinkedChildren;
- }
- else
- {
- targetItem.LinkedChildren = sourceItem.LinkedChildren.Concat(targetItem.LinkedChildren).Distinct().ToArray();
- }
+ targetItem.LinkedChildren = sourceItem.LinkedChildren.Concat(targetItem.LinkedChildren).Distinct().ToArray();
}
}
+ }
- /// <inheritdoc />
- protected override ItemUpdateType BeforeSaveInternal(BoxSet item, bool isFullRefresh, ItemUpdateType updateType)
- {
- var updatedType = base.BeforeSaveInternal(item, isFullRefresh, updateType);
-
- var libraryFolderIds = item.GetLibraryFolderIds();
+ /// <inheritdoc />
+ protected override ItemUpdateType BeforeSaveInternal(BoxSet item, bool isFullRefresh, ItemUpdateType updateType)
+ {
+ var updatedType = base.BeforeSaveInternal(item, isFullRefresh, updateType);
- var itemLibraryFolderIds = item.LibraryFolderIds;
- if (itemLibraryFolderIds is null || !libraryFolderIds.SequenceEqual(itemLibraryFolderIds))
- {
- item.LibraryFolderIds = libraryFolderIds;
- updatedType |= ItemUpdateType.MetadataImport;
- }
+ var libraryFolderIds = item.GetLibraryFolderIds();
- return updatedType;
+ var itemLibraryFolderIds = item.LibraryFolderIds;
+ if (itemLibraryFolderIds is null || !libraryFolderIds.SequenceEqual(itemLibraryFolderIds))
+ {
+ item.LibraryFolderIds = libraryFolderIds;
+ updatedType |= ItemUpdateType.MetadataImport;
}
+
+ return updatedType;
}
}
diff --git a/MediaBrowser.Providers/Channels/ChannelMetadataService.cs b/MediaBrowser.Providers/Channels/ChannelMetadataService.cs
index 0267fa13f..1285284aa 100644
--- a/MediaBrowser.Providers/Channels/ChannelMetadataService.cs
+++ b/MediaBrowser.Providers/Channels/ChannelMetadataService.cs
@@ -1,25 +1,36 @@
-#pragma warning disable CS1591
-
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Channels
+namespace MediaBrowser.Providers.Channels;
+
+/// <summary>
+/// Service to manage channel metadata.
+/// </summary>
+public class ChannelMetadataService : MetadataService<Channel, ItemLookupInfo>
{
- public class ChannelMetadataService : MetadataService<Channel, ItemLookupInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ChannelMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public ChannelMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<ChannelMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public ChannelMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<ChannelMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs b/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs
index 0629824d3..372b08090 100644
--- a/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs
+++ b/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs
@@ -1,25 +1,36 @@
-#pragma warning disable CS1591
-
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Folders
+namespace MediaBrowser.Providers.Folders;
+
+/// <summary>
+/// Service to manage collection folder metadata.
+/// </summary>
+public class CollectionFolderMetadataService : MetadataService<CollectionFolder, ItemLookupInfo>
{
- public class CollectionFolderMetadataService : MetadataService<CollectionFolder, ItemLookupInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CollectionFolderMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public CollectionFolderMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<CollectionFolderMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public CollectionFolderMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<CollectionFolderMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/Folders/FolderMetadataService.cs b/MediaBrowser.Providers/Folders/FolderMetadataService.cs
index 79d52991a..9ffb33abe 100644
--- a/MediaBrowser.Providers/Folders/FolderMetadataService.cs
+++ b/MediaBrowser.Providers/Folders/FolderMetadataService.cs
@@ -1,29 +1,40 @@
-#pragma warning disable CS1591
-
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Folders
+namespace MediaBrowser.Providers.Folders;
+
+/// <summary>
+/// Service to manage folder metadata.
+/// </summary>
+public class FolderMetadataService : MetadataService<Folder, ItemLookupInfo>
{
- public class FolderMetadataService : MetadataService<Folder, ItemLookupInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="FolderMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public FolderMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<FolderMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public FolderMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<FolderMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
-
- /// <inheritdoc />
- // Make sure the type-specific services get picked first
- public override int Order => 10;
}
+
+ /// <inheritdoc />
+ // Make sure the type-specific services get picked first
+ public override int Order => 10;
}
diff --git a/MediaBrowser.Providers/Folders/UserViewMetadataService.cs b/MediaBrowser.Providers/Folders/UserViewMetadataService.cs
index 79c5597e5..d0171aa8c 100644
--- a/MediaBrowser.Providers/Folders/UserViewMetadataService.cs
+++ b/MediaBrowser.Providers/Folders/UserViewMetadataService.cs
@@ -1,25 +1,36 @@
-#pragma warning disable CS1591
-
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Folders
+namespace MediaBrowser.Providers.Folders;
+
+/// <summary>
+/// Service to manage user view metadata.
+/// </summary>
+public class UserViewMetadataService : MetadataService<UserView, ItemLookupInfo>
{
- public class UserViewMetadataService : MetadataService<UserView, ItemLookupInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserViewMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public UserViewMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<UserViewMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public UserViewMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<UserViewMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/Genres/GenreMetadataService.cs b/MediaBrowser.Providers/Genres/GenreMetadataService.cs
index 4d10d8987..23aaf4c92 100644
--- a/MediaBrowser.Providers/Genres/GenreMetadataService.cs
+++ b/MediaBrowser.Providers/Genres/GenreMetadataService.cs
@@ -1,25 +1,36 @@
-#pragma warning disable CS1591
-
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Genres
+namespace MediaBrowser.Providers.Genres;
+
+/// <summary>
+/// Service to manage genre metadata.
+/// </summary>
+public class GenreMetadataService : MetadataService<Genre, ItemLookupInfo>
{
- public class GenreMetadataService : MetadataService<Genre, ItemLookupInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="GenreMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public GenreMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<GenreMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public GenreMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<GenreMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/LiveTv/LiveTvMetadataService.cs b/MediaBrowser.Providers/LiveTv/LiveTvMetadataService.cs
index c94d36530..c5c46f64c 100644
--- a/MediaBrowser.Providers/LiveTv/LiveTvMetadataService.cs
+++ b/MediaBrowser.Providers/LiveTv/LiveTvMetadataService.cs
@@ -1,6 +1,5 @@
-#pragma warning disable CS1591
-
using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.Providers;
@@ -8,18 +7,30 @@ using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.LiveTv
+namespace MediaBrowser.Providers.LiveTv;
+
+/// <summary>
+/// Service to manage live TV metadata.
+/// </summary>
+public class LiveTvMetadataService : MetadataService<LiveTvChannel, ItemLookupInfo>
{
- public class LiveTvMetadataService : MetadataService<LiveTvChannel, ItemLookupInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="LiveTvMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public LiveTvMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<LiveTvMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public LiveTvMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<LiveTvMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/Lyric/LrcLyricParser.cs b/MediaBrowser.Providers/Lyric/LrcLyricParser.cs
index fffdf4887..27d17b535 100644
--- a/MediaBrowser.Providers/Lyric/LrcLyricParser.cs
+++ b/MediaBrowser.Providers/Lyric/LrcLyricParser.cs
@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
+using System.Text.RegularExpressions;
using Jellyfin.Extensions;
using LrcParser.Model;
using LrcParser.Parser;
@@ -14,7 +15,7 @@ namespace MediaBrowser.Providers.Lyric;
/// <summary>
/// LRC Lyric Parser.
/// </summary>
-public class LrcLyricParser : ILyricParser
+public partial class LrcLyricParser : ILyricParser
{
private readonly LyricParser _lrcLyricParser;
@@ -65,13 +66,47 @@ public class LrcLyricParser : ILyricParser
}
List<LyricLine> lyricList = [];
-
- for (int i = 0; i < sortedLyricData.Count; i++)
+ for (var l = 0; l < sortedLyricData.Count; l++)
{
- long ticks = TimeSpan.FromMilliseconds(sortedLyricData[i].StartTime).Ticks;
- lyricList.Add(new LyricLine(sortedLyricData[i].Text.Trim(), ticks));
+ var cues = new List<LyricLineCue>();
+ var lyric = sortedLyricData[l];
+
+ if (lyric.TimeTags.Count != 0)
+ {
+ var keys = lyric.TimeTags.Keys.ToList();
+ int current = 0, next = 1;
+ while (next < keys.Count)
+ {
+ var currentKey = keys[current];
+ var currentMs = lyric.TimeTags[currentKey] ?? 0;
+ var nextMs = lyric.TimeTags[keys[next]] ?? 0;
+
+ cues.Add(new LyricLineCue(
+ position: Math.Max(currentKey.Index, 0),
+ start: TimeSpan.FromMilliseconds(currentMs).Ticks,
+ end: TimeSpan.FromMilliseconds(nextMs).Ticks));
+
+ current++;
+ next++;
+ }
+
+ var lastKey = keys[current];
+ var lastMs = lyric.TimeTags[lastKey] ?? 0;
+
+ cues.Add(new LyricLineCue(
+ position: Math.Max(lastKey.Index, 0),
+ start: TimeSpan.FromMilliseconds(lastMs).Ticks,
+ end: l + 1 < sortedLyricData.Count ? TimeSpan.FromMilliseconds(sortedLyricData[l + 1].StartTime).Ticks : null));
+ }
+
+ long lyricStartTicks = TimeSpan.FromMilliseconds(lyric.StartTime).Ticks;
+ lyricList.Add(new LyricLine(WhitespaceRegex().Replace(lyric.Text.Trim(), " "), lyricStartTicks, cues));
}
return new LyricDto { Lyrics = lyricList };
}
+
+ // Replacement is required until https://github.com/karaoke-dev/LrcParser/issues/83 is resolved.
+ [GeneratedRegex(@"\s+")]
+ private static partial Regex WhitespaceRegex();
}
diff --git a/MediaBrowser.Providers/Lyric/LyricManager.cs b/MediaBrowser.Providers/Lyric/LyricManager.cs
index f4b18a8c1..913a104a0 100644
--- a/MediaBrowser.Providers/Lyric/LyricManager.cs
+++ b/MediaBrowser.Providers/Lyric/LyricManager.cs
@@ -78,7 +78,8 @@ public class LyricManager : ILyricManager
MediaPath = audio.Path,
SongName = audio.Name,
AlbumName = audio.Album,
- ArtistNames = audio.GetAllArtists().ToList(),
+ AlbumArtistsNames = audio.AlbumArtists,
+ ArtistNames = audio.Artists,
Duration = audio.RunTimeTicks,
IsAutomated = isAutomated
};
diff --git a/MediaBrowser.Providers/Lyric/LyricScheduledTask.cs b/MediaBrowser.Providers/Lyric/LyricScheduledTask.cs
index 73912b579..b8861ee5e 100644
--- a/MediaBrowser.Providers/Lyric/LyricScheduledTask.cs
+++ b/MediaBrowser.Providers/Lyric/LyricScheduledTask.cs
@@ -117,7 +117,8 @@ public class LyricScheduledTask : IScheduledTask
MediaPath = audioItem.Path,
SongName = audioItem.Name,
AlbumName = audioItem.Album,
- ArtistNames = audioItem.GetAllArtists().ToList(),
+ AlbumArtistsNames = audioItem.AlbumArtists,
+ ArtistNames = audioItem.Artists,
Duration = audioItem.RunTimeTicks,
IsAutomated = true,
DisabledLyricFetchers = libraryOptions.DisabledLyricFetchers,
diff --git a/MediaBrowser.Providers/Manager/ImageSaver.cs b/MediaBrowser.Providers/Manager/ImageSaver.cs
index 8f6aa2db3..d9a8c044b 100644
--- a/MediaBrowser.Providers/Manager/ImageSaver.cs
+++ b/MediaBrowser.Providers/Manager/ImageSaver.cs
@@ -483,6 +483,22 @@ namespace MediaBrowser.Providers.Manager
}
}
+ if (type == ImageType.Logo && saveLocally)
+ {
+ if (season is not null && season.IndexNumber.HasValue)
+ {
+ var seriesFolder = season.SeriesPath;
+
+ var seasonMarker = season.IndexNumber.Value == 0
+ ? "-specials"
+ : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
+
+ var imageFilename = "season" + seasonMarker + "-logo" + extension;
+
+ return Path.Combine(seriesFolder, imageFilename);
+ }
+ }
+
string filename;
var folderName = item is MusicAlbum ||
item is MusicArtist ||
diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs
index 2cb381409..3aada3cef 100644
--- a/MediaBrowser.Providers/Manager/MetadataService.cs
+++ b/MediaBrowser.Providers/Manager/MetadataService.cs
@@ -12,6 +12,7 @@ using Jellyfin.Extensions;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Configuration;
@@ -26,13 +27,20 @@ namespace MediaBrowser.Providers.Manager
where TItemType : BaseItem, IHasLookupInfo<TIdType>, new()
where TIdType : ItemLookupInfo, new()
{
- protected MetadataService(IServerConfigurationManager serverConfigurationManager, ILogger<MetadataService<TItemType, TIdType>> logger, IProviderManager providerManager, IFileSystem fileSystem, ILibraryManager libraryManager)
+ protected MetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<MetadataService<TItemType, TIdType>> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
{
ServerConfigurationManager = serverConfigurationManager;
Logger = logger;
ProviderManager = providerManager;
FileSystem = fileSystem;
LibraryManager = libraryManager;
+ ExternalDataManager = externalDataManager;
ImageProvider = new ItemImageProvider(Logger, ProviderManager, FileSystem);
}
@@ -48,6 +56,8 @@ namespace MediaBrowser.Providers.Manager
protected ILibraryManager LibraryManager { get; }
+ protected IExternalDataManager ExternalDataManager { get; }
+
protected virtual bool EnableUpdatingPremiereDateFromChildren => false;
protected virtual bool EnableUpdatingGenresFromChildren => false;
@@ -76,7 +86,7 @@ namespace MediaBrowser.Providers.Manager
var itemOfType = (TItemType)item;
var updateType = ItemUpdateType.None;
var libraryOptions = LibraryManager.GetLibraryOptions(item);
- var isFirstRefresh = item.DateLastRefreshed == default;
+ var isFirstRefresh = item.DateLastRefreshed.Date == DateTime.MinValue.Date;
var hasRefreshedMetadata = true;
var hasRefreshedImages = true;
@@ -128,8 +138,7 @@ namespace MediaBrowser.Providers.Manager
var metadataResult = new MetadataResult<TItemType>
{
- Item = itemOfType,
- People = LibraryManager.GetPeople(item)
+ Item = itemOfType
};
var beforeSaveResult = BeforeSave(itemOfType, isFirstRefresh || refreshOptions.ReplaceAllMetadata || refreshOptions.MetadataRefreshMode == MetadataRefreshMode.FullRefresh || requiresRefresh || refreshOptions.ForceSave, updateType);
@@ -193,6 +202,7 @@ namespace MediaBrowser.Providers.Manager
if (hasRefreshedMetadata && hasRefreshedImages)
{
item.DateLastRefreshed = DateTime.UtcNow;
+ updateType |= item.OnMetadataChanged();
}
updateType = await SaveInternal(item, refreshOptions, updateType, isFirstRefresh, requiresRefresh, metadataResult, cancellationToken).ConfigureAwait(false);
@@ -252,7 +262,7 @@ namespace MediaBrowser.Providers.Manager
protected async Task SaveItemAsync(MetadataResult<TItemType> result, ItemUpdateType reason, CancellationToken cancellationToken)
{
- if (result.Item.SupportsPeople)
+ if (result.Item.SupportsPeople && result.People is not null)
{
var baseItem = result.Item;
@@ -303,6 +313,33 @@ namespace MediaBrowser.Providers.Manager
updateType |= ItemUpdateType.MetadataImport;
}
+ // Cleanup extracted files if source file was modified
+ var itemPath = item.Path;
+ if (!string.IsNullOrEmpty(itemPath))
+ {
+ var info = FileSystem.GetFileSystemInfo(itemPath);
+ var modificationDate = info.LastWriteTimeUtc;
+ var itemLastModifiedFileSystem = item.DateModified;
+ if (info.Exists && itemLastModifiedFileSystem != modificationDate)
+ {
+ Logger.LogDebug("File modification time changed from {Then} to {Now}: {Path}", itemLastModifiedFileSystem, modificationDate, itemPath);
+
+ item.DateModified = modificationDate;
+ if (ServerConfigurationManager.GetMetadataConfiguration().UseFileCreationTimeForDateAdded)
+ {
+ item.DateCreated = info.CreationTimeUtc;
+ }
+
+ if (item is Video video)
+ {
+ Logger.LogInformation("File changed, pruning extracted data: {Path}", item.Path);
+ ExternalDataManager.DeleteExternalItemDataAsync(video, CancellationToken.None).GetAwaiter().GetResult();
+ }
+
+ updateType |= ItemUpdateType.MetadataImport;
+ }
+ }
+
return updateType;
}
@@ -613,7 +650,7 @@ namespace MediaBrowser.Providers.Manager
var dateLastImageRefresh = item.DateLastRefreshed;
// Run all if either of these flags are true
- var runAllProviders = options.ImageRefreshMode == MetadataRefreshMode.FullRefresh || dateLastImageRefresh == default(DateTime);
+ var runAllProviders = options.ImageRefreshMode == MetadataRefreshMode.FullRefresh || dateLastImageRefresh.Date == DateTime.MinValue.Date;
if (!runAllProviders)
{
@@ -1043,7 +1080,7 @@ namespace MediaBrowser.Providers.Manager
}
else
{
- target.Studios = target.Studios.Concat(source.Studios).Distinct().ToArray();
+ target.Studios = target.Studios.Concat(source.Studios).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
}
}
@@ -1055,7 +1092,7 @@ namespace MediaBrowser.Providers.Manager
}
else
{
- target.Tags = target.Tags.Concat(source.Tags).Distinct().ToArray();
+ target.Tags = target.Tags.Concat(source.Tags).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
}
}
@@ -1067,7 +1104,7 @@ namespace MediaBrowser.Providers.Manager
}
else
{
- target.ProductionLocations = target.ProductionLocations.Concat(source.ProductionLocations).Distinct().ToArray();
+ target.ProductionLocations = target.ProductionLocations.Concat(source.ProductionLocations).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
}
}
@@ -1134,6 +1171,11 @@ namespace MediaBrowser.Providers.Manager
target.DateCreated = source.DateCreated;
}
+ if (replaceData || source.DateModified != default)
+ {
+ target.DateModified = source.DateModified;
+ }
+
if (replaceData || string.IsNullOrEmpty(target.PreferredMetadataCountryCode))
{
target.PreferredMetadataCountryCode = source.PreferredMetadataCountryCode;
@@ -1216,7 +1258,7 @@ namespace MediaBrowser.Providers.Manager
}
else if (sourceHasAlbumArtist.AlbumArtists.Count > 0)
{
- targetHasAlbumArtist.AlbumArtists = targetHasAlbumArtist.AlbumArtists.Concat(sourceHasAlbumArtist.AlbumArtists).Distinct().ToArray();
+ targetHasAlbumArtist.AlbumArtists = targetHasAlbumArtist.AlbumArtists.Concat(sourceHasAlbumArtist.AlbumArtists).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
}
}
}
diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs
index 856f33b49..1a29548f2 100644
--- a/MediaBrowser.Providers/Manager/ProviderManager.cs
+++ b/MediaBrowser.Providers/Manager/ProviderManager.cs
@@ -1,13 +1,11 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
-using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mime;
-using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using AsyncKeyedLock;
@@ -24,6 +22,7 @@ using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Lyrics;
+using MediaBrowser.Controller.MediaSegments;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Model.Configuration;
diff --git a/MediaBrowser.Providers/MediaInfo/AudioFileProber.cs b/MediaBrowser.Providers/MediaInfo/AudioFileProber.cs
index 916e2625b..cbbb7e83e 100644
--- a/MediaBrowser.Providers/MediaInfo/AudioFileProber.cs
+++ b/MediaBrowser.Providers/MediaInfo/AudioFileProber.cs
@@ -32,7 +32,6 @@ namespace MediaBrowser.Providers.MediaInfo
private const char InternalValueSeparator = '\u001F';
private readonly IMediaEncoder _mediaEncoder;
- private readonly IItemRepository _itemRepo;
private readonly ILibraryManager _libraryManager;
private readonly ILogger<AudioFileProber> _logger;
private readonly IMediaSourceManager _mediaSourceManager;
@@ -46,7 +45,6 @@ namespace MediaBrowser.Providers.MediaInfo
/// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
/// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
/// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
- /// <param name="itemRepo">Instance of the <see cref="IItemRepository"/> interface.</param>
/// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
/// <param name="lyricResolver">Instance of the <see cref="LyricResolver"/> interface.</param>
/// <param name="lyricManager">Instance of the <see cref="ILyricManager"/> interface.</param>
@@ -55,14 +53,12 @@ namespace MediaBrowser.Providers.MediaInfo
ILogger<AudioFileProber> logger,
IMediaSourceManager mediaSourceManager,
IMediaEncoder mediaEncoder,
- IItemRepository itemRepo,
ILibraryManager libraryManager,
LyricResolver lyricResolver,
ILyricManager lyricManager,
IMediaStreamRepository mediaStreamRepository)
{
_mediaEncoder = mediaEncoder;
- _itemRepo = itemRepo;
_libraryManager = libraryManager;
_logger = logger;
_mediaSourceManager = mediaSourceManager;
@@ -137,7 +133,6 @@ namespace MediaBrowser.Providers.MediaInfo
audio.TotalBitrate = mediaInfo.Bitrate;
audio.RunTimeTicks = mediaInfo.RunTimeTicks;
- audio.Size = mediaInfo.Size;
// Add external lyrics first to prevent the lrc file get overwritten on first scan
var mediaStreams = new List<MediaStream>(mediaInfo.MediaStreams);
@@ -180,16 +175,24 @@ namespace MediaBrowser.Providers.MediaInfo
// That setter is meant for its own tag parser and external editor usage and will have unwanted side effects
// For example, setting the Year property will also set the Date property, which is not what we want here.
// 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 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 trackTrackNumber = track.TrackNumber is null or 0 ? mediaInfo.IndexNumber : track.TrackNumber;
var trackDiscNumber = track.DiscNumber is null or 0 ? mediaInfo.ParentIndexNumber : track.DiscNumber;
+ // Some users may use a misbehaved tag editor that writes a null character in the tag when not allowed by the standard.
+ trackTitle = GetSanitizedStringTag(trackTitle, audio.Path);
+ trackAlbum = GetSanitizedStringTag(trackAlbum, audio.Path);
+ var trackAlbumArtist = GetSanitizedStringTag(track.AlbumArtist, audio.Path);
+ var trackArist = GetSanitizedStringTag(track.Artist, audio.Path);
+ var trackComposer = GetSanitizedStringTag(track.Composer, audio.Path);
+ var trackGenre = GetSanitizedStringTag(track.Genre, audio.Path);
+
if (audio.SupportsPeople && !audio.LockedFields.Contains(MetadataField.Cast))
{
var people = new List<PersonInfo>();
- var albumArtists = string.IsNullOrEmpty(track.AlbumArtist) ? [] : track.AlbumArtist.Split(InternalValueSeparator);
+ var albumArtists = string.IsNullOrEmpty(trackAlbumArtist) ? [] : trackAlbumArtist.Split(InternalValueSeparator);
if (libraryOptions.UseCustomTagDelimiters)
{
@@ -211,7 +214,7 @@ namespace MediaBrowser.Providers.MediaInfo
string[]? performers = null;
if (libraryOptions.PreferNonstandardArtistsTag)
{
- track.AdditionalFields.TryGetValue("ARTISTS", out var artistsTagString);
+ TryGetSanitizedAdditionalFields(track, "ARTISTS", out var artistsTagString);
if (artistsTagString is not null)
{
performers = artistsTagString.Split(InternalValueSeparator);
@@ -220,7 +223,7 @@ namespace MediaBrowser.Providers.MediaInfo
if (performers is null || performers.Length == 0)
{
- performers = string.IsNullOrEmpty(track.Artist) ? [] : track.Artist.Split(InternalValueSeparator);
+ performers = string.IsNullOrEmpty(trackArist) ? [] : trackArist.Split(InternalValueSeparator);
}
if (libraryOptions.UseCustomTagDelimiters)
@@ -240,15 +243,18 @@ namespace MediaBrowser.Providers.MediaInfo
}
}
- foreach (var composer in track.Composer.Split(InternalValueSeparator))
+ if (!string.IsNullOrWhiteSpace(trackComposer))
{
- if (!string.IsNullOrWhiteSpace(composer))
+ foreach (var composer in trackComposer.Split(InternalValueSeparator))
{
- PeopleHelper.AddPerson(people, new PersonInfo
+ if (!string.IsNullOrWhiteSpace(composer))
{
- Name = composer.Trim(),
- Type = PersonKind.Composer
- });
+ PeopleHelper.AddPerson(people, new PersonInfo
+ {
+ Name = composer.Trim(),
+ Type = PersonKind.Composer
+ });
+ }
}
}
@@ -325,7 +331,7 @@ namespace MediaBrowser.Providers.MediaInfo
if (!audio.LockedFields.Contains(MetadataField.Genres))
{
- var genres = string.IsNullOrEmpty(track.Genre) ? [] : track.Genre.Split(InternalValueSeparator).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
+ var genres = string.IsNullOrEmpty(trackGenre) ? [] : trackGenre.Split(InternalValueSeparator).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
if (libraryOptions.UseCustomTagDelimiters)
{
@@ -339,7 +345,7 @@ namespace MediaBrowser.Providers.MediaInfo
: audio.Genres;
}
- track.AdditionalFields.TryGetValue("REPLAYGAIN_TRACK_GAIN", out var trackGainTag);
+ TryGetSanitizedAdditionalFields(track, "REPLAYGAIN_TRACK_GAIN", out var trackGainTag);
if (trackGainTag is not null)
{
@@ -348,7 +354,7 @@ namespace MediaBrowser.Providers.MediaInfo
trackGainTag = trackGainTag[..^2].Trim();
}
- if (float.TryParse(trackGainTag, NumberStyles.Float, CultureInfo.InvariantCulture, out var value))
+ if (float.TryParse(trackGainTag, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) && float.IsFinite(value))
{
audio.NormalizationGain = value;
}
@@ -356,8 +362,8 @@ namespace MediaBrowser.Providers.MediaInfo
if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzArtist, out _))
{
- if ((track.AdditionalFields.TryGetValue("MUSICBRAINZ_ARTISTID", out var musicBrainzArtistTag)
- || track.AdditionalFields.TryGetValue("MusicBrainz Artist Id", out musicBrainzArtistTag))
+ if ((TryGetSanitizedAdditionalFields(track, "MUSICBRAINZ_ARTISTID", out var musicBrainzArtistTag)
+ || TryGetSanitizedAdditionalFields(track, "MusicBrainz Artist Id", out musicBrainzArtistTag))
&& !string.IsNullOrEmpty(musicBrainzArtistTag))
{
var id = GetFirstMusicBrainzId(musicBrainzArtistTag, libraryOptions.UseCustomTagDelimiters, libraryOptions.GetCustomTagDelimiters(), libraryOptions.DelimiterWhitelist);
@@ -367,8 +373,8 @@ namespace MediaBrowser.Providers.MediaInfo
if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzAlbumArtist, out _))
{
- if ((track.AdditionalFields.TryGetValue("MUSICBRAINZ_ALBUMARTISTID", out var musicBrainzReleaseArtistIdTag)
- || track.AdditionalFields.TryGetValue("MusicBrainz Album Artist Id", out musicBrainzReleaseArtistIdTag))
+ if ((TryGetSanitizedAdditionalFields(track, "MUSICBRAINZ_ALBUMARTISTID", out var musicBrainzReleaseArtistIdTag)
+ || TryGetSanitizedAdditionalFields(track, "MusicBrainz Album Artist Id", out musicBrainzReleaseArtistIdTag))
&& !string.IsNullOrEmpty(musicBrainzReleaseArtistIdTag))
{
var id = GetFirstMusicBrainzId(musicBrainzReleaseArtistIdTag, libraryOptions.UseCustomTagDelimiters, libraryOptions.GetCustomTagDelimiters(), libraryOptions.DelimiterWhitelist);
@@ -378,8 +384,8 @@ namespace MediaBrowser.Providers.MediaInfo
if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzAlbum, out _))
{
- if ((track.AdditionalFields.TryGetValue("MUSICBRAINZ_ALBUMID", out var musicBrainzReleaseIdTag)
- || track.AdditionalFields.TryGetValue("MusicBrainz Album Id", out musicBrainzReleaseIdTag))
+ if ((TryGetSanitizedAdditionalFields(track, "MUSICBRAINZ_ALBUMID", out var musicBrainzReleaseIdTag)
+ || TryGetSanitizedAdditionalFields(track, "MusicBrainz Album Id", out musicBrainzReleaseIdTag))
&& !string.IsNullOrEmpty(musicBrainzReleaseIdTag))
{
var id = GetFirstMusicBrainzId(musicBrainzReleaseIdTag, libraryOptions.UseCustomTagDelimiters, libraryOptions.GetCustomTagDelimiters(), libraryOptions.DelimiterWhitelist);
@@ -389,8 +395,8 @@ namespace MediaBrowser.Providers.MediaInfo
if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzReleaseGroup, out _))
{
- if ((track.AdditionalFields.TryGetValue("MUSICBRAINZ_RELEASEGROUPID", out var musicBrainzReleaseGroupIdTag)
- || track.AdditionalFields.TryGetValue("MusicBrainz Release Group Id", out musicBrainzReleaseGroupIdTag))
+ if ((TryGetSanitizedAdditionalFields(track, "MUSICBRAINZ_RELEASEGROUPID", out var musicBrainzReleaseGroupIdTag)
+ || TryGetSanitizedAdditionalFields(track, "MusicBrainz Release Group Id", out musicBrainzReleaseGroupIdTag))
&& !string.IsNullOrEmpty(musicBrainzReleaseGroupIdTag))
{
var id = GetFirstMusicBrainzId(musicBrainzReleaseGroupIdTag, libraryOptions.UseCustomTagDelimiters, libraryOptions.GetCustomTagDelimiters(), libraryOptions.DelimiterWhitelist);
@@ -400,8 +406,8 @@ namespace MediaBrowser.Providers.MediaInfo
if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzTrack, out _))
{
- if ((track.AdditionalFields.TryGetValue("MUSICBRAINZ_RELEASETRACKID", out var trackMbId)
- || track.AdditionalFields.TryGetValue("MusicBrainz Release Track Id", out trackMbId))
+ if ((TryGetSanitizedAdditionalFields(track, "MUSICBRAINZ_RELEASETRACKID", out var trackMbId)
+ || TryGetSanitizedAdditionalFields(track, "MusicBrainz Release Track Id", out trackMbId))
&& !string.IsNullOrEmpty(trackMbId))
{
var id = GetFirstMusicBrainzId(trackMbId, libraryOptions.UseCustomTagDelimiters, libraryOptions.GetCustomTagDelimiters(), libraryOptions.DelimiterWhitelist);
@@ -411,13 +417,13 @@ namespace MediaBrowser.Providers.MediaInfo
if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzRecording, out _))
{
- if ((track.AdditionalFields.TryGetValue("MUSICBRAINZ_TRACKID", out var recordingMbId)
- || track.AdditionalFields.TryGetValue("MusicBrainz Track Id", out recordingMbId))
+ if ((TryGetSanitizedAdditionalFields(track, "MUSICBRAINZ_TRACKID", out var recordingMbId)
+ || TryGetSanitizedAdditionalFields(track, "MusicBrainz Track Id", out recordingMbId))
&& !string.IsNullOrEmpty(recordingMbId))
{
audio.TrySetProviderId(MetadataProvider.MusicBrainzRecording, recordingMbId);
}
- else if (track.AdditionalFields.TryGetValue("UFID", out var ufIdValue) && !string.IsNullOrEmpty(ufIdValue))
+ else if (TryGetSanitizedAdditionalFields(track, "UFID", out var ufIdValue) && !string.IsNullOrEmpty(ufIdValue))
{
// If tagged with MB Picard, the format is 'http://musicbrainz.org\0<recording MBID>'
if (ufIdValue.Contains("musicbrainz.org", StringComparison.OrdinalIgnoreCase))
@@ -490,5 +496,28 @@ namespace MediaBrowser.Providers.MediaInfo
return val;
}
+
+ private string? GetSanitizedStringTag(string? tag, string filePath)
+ {
+ if (string.IsNullOrEmpty(tag))
+ {
+ return null;
+ }
+
+ var result = tag.TruncateAtNull();
+ if (result.Length != tag.Length)
+ {
+ _logger.LogWarning("Audio file {File} contains a null character in its tag, but this is not allowed by its tagging standard. All characters after the null char will be discarded. Please fix your file", filePath);
+ }
+
+ return result;
+ }
+
+ private bool TryGetSanitizedAdditionalFields(Track track, string field, out string? value)
+ {
+ var hasField = track.AdditionalFields.TryGetValue(field, out value);
+ value = GetSanitizedStringTag(value, track.Path);
+ return hasField;
+ }
}
}
diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs
index 266e1861f..d85f49b1d 100644
--- a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs
+++ b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs
@@ -34,13 +34,11 @@ namespace MediaBrowser.Providers.MediaInfo
private readonly ILogger<FFProbeVideoInfo> _logger;
private readonly IMediaSourceManager _mediaSourceManager;
private readonly IMediaEncoder _mediaEncoder;
- private readonly IItemRepository _itemRepo;
private readonly IBlurayExaminer _blurayExaminer;
private readonly ILocalizationManager _localization;
- private readonly IEncodingManager _encodingManager;
+ private readonly IChapterManager _chapterManager;
private readonly IServerConfigurationManager _config;
private readonly ISubtitleManager _subtitleManager;
- private readonly IChapterRepository _chapterManager;
private readonly ILibraryManager _libraryManager;
private readonly AudioResolver _audioResolver;
private readonly SubtitleResolver _subtitleResolver;
@@ -51,13 +49,11 @@ namespace MediaBrowser.Providers.MediaInfo
ILogger<FFProbeVideoInfo> logger,
IMediaSourceManager mediaSourceManager,
IMediaEncoder mediaEncoder,
- IItemRepository itemRepo,
IBlurayExaminer blurayExaminer,
ILocalizationManager localization,
- IEncodingManager encodingManager,
+ IChapterManager chapterManager,
IServerConfigurationManager config,
ISubtitleManager subtitleManager,
- IChapterRepository chapterManager,
ILibraryManager libraryManager,
AudioResolver audioResolver,
SubtitleResolver subtitleResolver,
@@ -67,13 +63,11 @@ namespace MediaBrowser.Providers.MediaInfo
_logger = logger;
_mediaSourceManager = mediaSourceManager;
_mediaEncoder = mediaEncoder;
- _itemRepo = itemRepo;
_blurayExaminer = blurayExaminer;
_localization = localization;
- _encodingManager = encodingManager;
+ _chapterManager = chapterManager;
_config = config;
_subtitleManager = subtitleManager;
- _chapterManager = chapterManager;
_libraryManager = libraryManager;
_audioResolver = audioResolver;
_subtitleResolver = subtitleResolver;
@@ -220,10 +214,14 @@ namespace MediaBrowser.Providers.MediaInfo
mediaAttachments = mediaInfo.MediaAttachments;
video.TotalBitrate = mediaInfo.Bitrate;
video.RunTimeTicks = mediaInfo.RunTimeTicks;
- video.Size = mediaInfo.Size;
video.Container = mediaInfo.Container;
+ var videoType = video.VideoType;
+ if (videoType == VideoType.BluRay || videoType == VideoType.Dvd)
+ {
+ video.Size = mediaInfo.Size;
+ }
- chapters = mediaInfo.Chapters ?? Array.Empty<ChapterInfo>();
+ chapters = mediaInfo.Chapters ?? [];
if (blurayInfo is not null)
{
FetchBdInfo(video, ref chapters, mediaStreams, blurayInfo);
@@ -240,8 +238,8 @@ namespace MediaBrowser.Providers.MediaInfo
}
}
- mediaAttachments = Array.Empty<MediaAttachment>();
- chapters = Array.Empty<ChapterInfo>();
+ mediaAttachments = [];
+ chapters = [];
}
var libraryOptions = _libraryManager.GetLibraryOptions(video);
@@ -298,9 +296,9 @@ namespace MediaBrowser.Providers.MediaInfo
extractDuringScan = libraryOptions.ExtractChapterImagesDuringLibraryScan;
}
- await _encodingManager.RefreshChapterImages(video, options.DirectoryService, chapters, extractDuringScan, false, cancellationToken).ConfigureAwait(false);
+ await _chapterManager.RefreshChapterImages(video, options.DirectoryService, chapters, extractDuringScan, false, cancellationToken).ConfigureAwait(false);
- _chapterManager.SaveChapters(video.Id, chapters);
+ _chapterManager.SaveChapters(video, chapters);
}
}
@@ -324,16 +322,19 @@ namespace MediaBrowser.Providers.MediaInfo
private void FetchBdInfo(Video video, ref ChapterInfo[] chapters, List<MediaStream> mediaStreams, BlurayDiscInfo blurayInfo)
{
- if (blurayInfo.Files.Length <= 1)
- {
- return;
- }
-
var ffmpegVideoStream = mediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
+ var externalStreams = mediaStreams.Where(s => s.IsExternal).ToList();
// Fill video properties from the BDInfo result
mediaStreams.Clear();
- mediaStreams.AddRange(blurayInfo.MediaStreams);
+
+ // Rebuild the list with external streams first
+ int index = 0;
+ foreach (var stream in externalStreams.Concat(blurayInfo.MediaStreams))
+ {
+ stream.Index = index++;
+ mediaStreams.Add(stream);
+ }
if (blurayInfo.RunTimeTicks.HasValue && blurayInfo.RunTimeTicks.Value > 0)
{
@@ -406,7 +407,7 @@ namespace MediaBrowser.Providers.MediaInfo
{
if (video.Genres.Length == 0 || replaceData)
{
- video.Genres = Array.Empty<string>();
+ video.Genres = [];
foreach (var genre in data.Genres.Trimmed())
{
@@ -649,7 +650,7 @@ namespace MediaBrowser.Providers.MediaInfo
long dummyChapterDuration = TimeSpan.FromSeconds(_config.Configuration.DummyChapterDuration).Ticks;
if (runtime <= dummyChapterDuration)
{
- return Array.Empty<ChapterInfo>();
+ return [];
}
int chapterCount = (int)(runtime / dummyChapterDuration);
diff --git a/MediaBrowser.Providers/MediaInfo/ProbeProvider.cs b/MediaBrowser.Providers/MediaInfo/ProbeProvider.cs
index 1c2f8b913..8c673350d 100644
--- a/MediaBrowser.Providers/MediaInfo/ProbeProvider.cs
+++ b/MediaBrowser.Providers/MediaInfo/ProbeProvider.cs
@@ -55,13 +55,11 @@ namespace MediaBrowser.Providers.MediaInfo
/// </summary>
/// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
/// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
- /// <param name="itemRepo">Instance of the <see cref="IItemRepository"/> interface.</param>
/// <param name="blurayExaminer">Instance of the <see cref="IBlurayExaminer"/> interface.</param>
/// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
- /// <param name="encodingManager">Instance of the <see cref="IEncodingManager"/> interface.</param>
+ /// <param name="chapterManager">Instance of the <see cref="IChapterManager"/> interface.</param>
/// <param name="config">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
/// <param name="subtitleManager">Instance of the <see cref="ISubtitleManager"/> interface.</param>
- /// <param name="chapterManager">Instance of the <see cref="IChapterRepository"/> interface.</param>
/// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
/// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/>.</param>
/// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
@@ -72,13 +70,11 @@ namespace MediaBrowser.Providers.MediaInfo
public ProbeProvider(
IMediaSourceManager mediaSourceManager,
IMediaEncoder mediaEncoder,
- IItemRepository itemRepo,
IBlurayExaminer blurayExaminer,
ILocalizationManager localization,
- IEncodingManager encodingManager,
+ IChapterManager chapterManager,
IServerConfigurationManager config,
ISubtitleManager subtitleManager,
- IChapterRepository chapterManager,
ILibraryManager libraryManager,
IFileSystem fileSystem,
ILoggerFactory loggerFactory,
@@ -96,13 +92,11 @@ namespace MediaBrowser.Providers.MediaInfo
loggerFactory.CreateLogger<FFProbeVideoInfo>(),
mediaSourceManager,
mediaEncoder,
- itemRepo,
blurayExaminer,
localization,
- encodingManager,
+ chapterManager,
config,
subtitleManager,
- chapterManager,
libraryManager,
_audioResolver,
_subtitleResolver,
@@ -113,7 +107,6 @@ namespace MediaBrowser.Providers.MediaInfo
loggerFactory.CreateLogger<AudioFileProber>(),
mediaSourceManager,
mediaEncoder,
- itemRepo,
libraryManager,
_lyricResolver,
lyricManager,
@@ -137,9 +130,9 @@ namespace MediaBrowser.Providers.MediaInfo
if (!string.IsNullOrWhiteSpace(path) && item.IsFileProtocol)
{
var file = directoryService.GetFile(path);
- if (file is not null && file.LastWriteTimeUtc != item.DateModified)
+ if (file is not null && file.LastWriteTimeUtc != item.DateModified && file.Length != item.Size)
{
- _logger.LogDebug("Refreshing {ItemPath} due to date modified timestamp change.", path);
+ _logger.LogDebug("Refreshing {ItemPath} due to file system modification.", path);
return true;
}
}
diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs b/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs
index 938f3cb32..1134baf92 100644
--- a/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs
+++ b/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs
@@ -14,7 +14,6 @@ using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Subtitles;
-using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Tasks;
diff --git a/MediaBrowser.Providers/Movies/MovieMetadataService.cs b/MediaBrowser.Providers/Movies/MovieMetadataService.cs
index 8997ddc64..a6e1f424d 100644
--- a/MediaBrowser.Providers/Movies/MovieMetadataService.cs
+++ b/MediaBrowser.Providers/Movies/MovieMetadataService.cs
@@ -1,7 +1,6 @@
-#pragma warning disable CS1591
-
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
@@ -9,32 +8,44 @@ using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Movies
+namespace MediaBrowser.Providers.Movies;
+
+/// <summary>
+/// Service to manage movie metadata.
+/// </summary>
+public class MovieMetadataService : MetadataService<Movie, MovieInfo>
{
- public class MovieMetadataService : MetadataService<Movie, MovieInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MovieMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public MovieMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<MovieMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public MovieMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<MovieMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
+ }
- /// <inheritdoc />
- protected override void MergeData(MetadataResult<Movie> source, MetadataResult<Movie> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
- {
- base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Movie> source, MetadataResult<Movie> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ {
+ base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
- var sourceItem = source.Item;
- var targetItem = target.Item;
+ var sourceItem = source.Item;
+ var targetItem = target.Item;
- if (replaceData || string.IsNullOrEmpty(targetItem.CollectionName))
- {
- targetItem.CollectionName = sourceItem.CollectionName;
- }
+ if (replaceData || string.IsNullOrEmpty(targetItem.CollectionName))
+ {
+ targetItem.CollectionName = sourceItem.CollectionName;
}
}
}
diff --git a/MediaBrowser.Providers/Movies/TrailerMetadataService.cs b/MediaBrowser.Providers/Movies/TrailerMetadataService.cs
index e77d2fa8a..7f38861e3 100644
--- a/MediaBrowser.Providers/Movies/TrailerMetadataService.cs
+++ b/MediaBrowser.Providers/Movies/TrailerMetadataService.cs
@@ -1,8 +1,7 @@
-#pragma warning disable CS1591
-
using System.Linq;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
@@ -10,33 +9,45 @@ using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Movies
+namespace MediaBrowser.Providers.Movies;
+
+/// <summary>
+/// Service to manage trailer metadata.
+/// </summary>
+public class TrailerMetadataService : MetadataService<Trailer, TrailerInfo>
{
- public class TrailerMetadataService : MetadataService<Trailer, TrailerInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TrailerMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public TrailerMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<TrailerMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
+ {
+ }
+
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Trailer> source, MetadataResult<Trailer> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
{
- public TrailerMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<TrailerMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
+ base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
+
+ if (replaceData || target.Item.TrailerTypes.Length == 0)
{
+ target.Item.TrailerTypes = source.Item.TrailerTypes;
}
-
- /// <inheritdoc />
- protected override void MergeData(MetadataResult<Trailer> source, MetadataResult<Trailer> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ else
{
- base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
-
- if (replaceData || target.Item.TrailerTypes.Length == 0)
- {
- target.Item.TrailerTypes = source.Item.TrailerTypes;
- }
- else
- {
- target.Item.TrailerTypes = target.Item.TrailerTypes.Concat(source.Item.TrailerTypes).Distinct().ToArray();
- }
+ target.Item.TrailerTypes = target.Item.TrailerTypes.Concat(source.Item.TrailerTypes).Distinct().ToArray();
}
}
}
diff --git a/MediaBrowser.Providers/Music/AlbumMetadataService.cs b/MediaBrowser.Providers/Music/AlbumMetadataService.cs
index 0bcc301cb..2af3667d0 100644
--- a/MediaBrowser.Providers/Music/AlbumMetadataService.cs
+++ b/MediaBrowser.Providers/Music/AlbumMetadataService.cs
@@ -5,6 +5,7 @@ using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
@@ -12,238 +13,239 @@ using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Music
+namespace MediaBrowser.Providers.Music;
+
+/// <summary>
+/// The album metadata service.
+/// </summary>
+public class AlbumMetadataService : MetadataService<MusicAlbum, AlbumInfo>
{
/// <summary>
- /// The album metadata service.
+ /// Initializes a new instance of the <see cref="AlbumMetadataService"/> class.
/// </summary>
- public class AlbumMetadataService : MetadataService<MusicAlbum, AlbumInfo>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public AlbumMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<AlbumMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- /// <summary>
- /// Initializes a new instance of the <see cref="AlbumMetadataService"/> class.
- /// </summary>
- /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
- /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
- /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
- /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
- /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
- public AlbumMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<AlbumMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
+ }
+
+ /// <inheritdoc />
+ protected override bool EnableUpdatingPremiereDateFromChildren => true;
- /// <inheritdoc />
- protected override bool EnableUpdatingPremiereDateFromChildren => true;
+ /// <inheritdoc />
+ protected override bool EnableUpdatingGenresFromChildren => true;
- /// <inheritdoc />
- protected override bool EnableUpdatingGenresFromChildren => true;
+ /// <inheritdoc />
+ protected override bool EnableUpdatingStudiosFromChildren => true;
- /// <inheritdoc />
- protected override bool EnableUpdatingStudiosFromChildren => true;
+ /// <inheritdoc />
+ protected override IReadOnlyList<BaseItem> GetChildrenForMetadataUpdates(MusicAlbum item)
+ => item.GetRecursiveChildren(i => i is Audio);
- /// <inheritdoc />
- protected override IReadOnlyList<BaseItem> GetChildrenForMetadataUpdates(MusicAlbum item)
- => item.GetRecursiveChildren(i => i is Audio);
+ /// <inheritdoc />
+ protected override ItemUpdateType UpdateMetadataFromChildren(MusicAlbum item, IReadOnlyList<BaseItem> children, bool isFullRefresh, ItemUpdateType currentUpdateType)
+ {
+ var updateType = base.UpdateMetadataFromChildren(item, children, isFullRefresh, currentUpdateType);
- /// <inheritdoc />
- protected override ItemUpdateType UpdateMetadataFromChildren(MusicAlbum item, IReadOnlyList<BaseItem> children, bool isFullRefresh, ItemUpdateType currentUpdateType)
+ // don't update user-changeable metadata for locked items
+ if (item.IsLocked)
{
- var updateType = base.UpdateMetadataFromChildren(item, children, isFullRefresh, currentUpdateType);
+ return updateType;
+ }
- // don't update user-changeable metadata for locked items
- if (item.IsLocked)
+ if (isFullRefresh || currentUpdateType > ItemUpdateType.None)
+ {
+ if (!item.LockedFields.Contains(MetadataField.Name))
{
- return updateType;
- }
+ var name = children.Select(i => i.Album).FirstOrDefault(i => !string.IsNullOrEmpty(i));
- if (isFullRefresh || currentUpdateType > ItemUpdateType.None)
- {
- if (!item.LockedFields.Contains(MetadataField.Name))
+ if (!string.IsNullOrEmpty(name)
+ && !string.Equals(item.Name, name, StringComparison.Ordinal))
{
- var name = children.Select(i => i.Album).FirstOrDefault(i => !string.IsNullOrEmpty(i));
-
- if (!string.IsNullOrEmpty(name)
- && !string.Equals(item.Name, name, StringComparison.Ordinal))
- {
- item.Name = name;
- updateType |= ItemUpdateType.MetadataEdit;
- }
+ item.Name = name;
+ updateType |= ItemUpdateType.MetadataEdit;
}
-
- var songs = children.Cast<Audio>().ToArray();
-
- updateType |= SetArtistsFromSongs(item, songs);
- updateType |= SetAlbumArtistFromSongs(item, songs);
- updateType |= SetAlbumFromSongs(item, songs);
- updateType |= SetPeople(item);
}
- return updateType;
+ var songs = children.Cast<Audio>().ToArray();
+
+ updateType |= SetArtistsFromSongs(item, songs);
+ updateType |= SetAlbumArtistFromSongs(item, songs);
+ updateType |= SetAlbumFromSongs(item, songs);
+ updateType |= SetPeople(item);
}
- private ItemUpdateType SetAlbumArtistFromSongs(MusicAlbum item, IReadOnlyList<Audio> songs)
- {
- var updateType = ItemUpdateType.None;
+ return updateType;
+ }
- var albumArtists = songs
- .SelectMany(i => i.AlbumArtists)
- .GroupBy(i => i)
- .OrderByDescending(g => g.Count())
- .Select(g => g.Key)
- .ToArray();
+ private ItemUpdateType SetAlbumArtistFromSongs(MusicAlbum item, IReadOnlyList<Audio> songs)
+ {
+ var updateType = ItemUpdateType.None;
- updateType |= SetProviderIdFromSongs(item, songs, MetadataProvider.MusicBrainzAlbumArtist);
+ var albumArtists = songs
+ .SelectMany(i => i.AlbumArtists)
+ .GroupBy(i => i)
+ .OrderByDescending(g => g.Count())
+ .Select(g => g.Key)
+ .ToArray();
- if (!item.AlbumArtists.SequenceEqual(albumArtists, StringComparer.OrdinalIgnoreCase))
- {
- item.AlbumArtists = albumArtists;
- updateType |= ItemUpdateType.MetadataEdit;
- }
+ updateType |= SetProviderIdFromSongs(item, songs, MetadataProvider.MusicBrainzAlbumArtist);
- return updateType;
+ if (!item.AlbumArtists.SequenceEqual(albumArtists, StringComparer.OrdinalIgnoreCase))
+ {
+ item.AlbumArtists = albumArtists;
+ updateType |= ItemUpdateType.MetadataEdit;
}
- private ItemUpdateType SetArtistsFromSongs(MusicAlbum item, IReadOnlyList<Audio> songs)
- {
- var updateType = ItemUpdateType.None;
+ return updateType;
+ }
- var artists = songs
- .SelectMany(i => i.Artists)
- .GroupBy(i => i)
- .OrderByDescending(g => g.Count())
- .Select(g => g.Key)
- .ToArray();
+ private ItemUpdateType SetArtistsFromSongs(MusicAlbum item, IReadOnlyList<Audio> songs)
+ {
+ var updateType = ItemUpdateType.None;
- if (!item.Artists.SequenceEqual(artists, StringComparer.OrdinalIgnoreCase))
- {
- item.Artists = artists;
- updateType |= ItemUpdateType.MetadataEdit;
- }
+ var artists = songs
+ .SelectMany(i => i.Artists)
+ .GroupBy(i => i)
+ .OrderByDescending(g => g.Count())
+ .Select(g => g.Key)
+ .ToArray();
- return updateType;
+ if (!item.Artists.SequenceEqual(artists, StringComparer.OrdinalIgnoreCase))
+ {
+ item.Artists = artists;
+ updateType |= ItemUpdateType.MetadataEdit;
}
- private ItemUpdateType SetAlbumFromSongs(MusicAlbum item, IReadOnlyList<Audio> songs)
- {
- var updateType = ItemUpdateType.None;
+ return updateType;
+ }
- updateType |= SetProviderIdFromSongs(item, songs, MetadataProvider.MusicBrainzAlbum);
- updateType |= SetProviderIdFromSongs(item, songs, MetadataProvider.MusicBrainzReleaseGroup);
+ private ItemUpdateType SetAlbumFromSongs(MusicAlbum item, IReadOnlyList<Audio> songs)
+ {
+ var updateType = ItemUpdateType.None;
- return updateType;
- }
+ updateType |= SetProviderIdFromSongs(item, songs, MetadataProvider.MusicBrainzAlbum);
+ updateType |= SetProviderIdFromSongs(item, songs, MetadataProvider.MusicBrainzReleaseGroup);
- private ItemUpdateType SetProviderIdFromSongs(BaseItem item, IReadOnlyList<Audio> songs, MetadataProvider provider)
+ return updateType;
+ }
+
+ private ItemUpdateType SetProviderIdFromSongs(BaseItem item, IReadOnlyList<Audio> songs, MetadataProvider provider)
+ {
+ var ids = songs
+ .Select(i => i.GetProviderId(provider))
+ .GroupBy(i => i)
+ .OrderByDescending(g => g.Count())
+ .Select(g => g.Key)
+ .ToArray();
+
+ var id = item.GetProviderId(provider);
+ if (ids.Length != 0)
{
- var ids = songs
- .Select(i => i.GetProviderId(provider))
- .GroupBy(i => i)
- .OrderByDescending(g => g.Count())
- .Select(g => g.Key)
- .ToArray();
-
- var id = item.GetProviderId(provider);
- if (ids.Length != 0)
+ var firstId = ids[0];
+ if (!string.IsNullOrEmpty(firstId)
+ && (string.IsNullOrEmpty(id)
+ || !id.Equals(firstId, StringComparison.OrdinalIgnoreCase)))
{
- var firstId = ids[0];
- if (!string.IsNullOrEmpty(firstId)
- && (string.IsNullOrEmpty(id)
- || !id.Equals(firstId, StringComparison.OrdinalIgnoreCase)))
- {
- item.SetProviderId(provider, firstId);
- return ItemUpdateType.MetadataEdit;
- }
+ item.SetProviderId(provider, firstId);
+ return ItemUpdateType.MetadataEdit;
}
-
- return ItemUpdateType.None;
}
- private void SetProviderId(MusicAlbum sourceItem, MusicAlbum targetItem, MetadataProvider provider)
+ return ItemUpdateType.None;
+ }
+
+ private void SetProviderId(MusicAlbum sourceItem, MusicAlbum targetItem, MetadataProvider provider)
+ {
+ var source = sourceItem.GetProviderId(provider);
+ var target = targetItem.GetProviderId(provider);
+ if (!string.IsNullOrEmpty(source)
+ && (string.IsNullOrEmpty(target)
+ || !target.Equals(source, StringComparison.Ordinal)))
{
- var source = sourceItem.GetProviderId(provider);
- var target = targetItem.GetProviderId(provider);
- if (!string.IsNullOrEmpty(source)
- && (string.IsNullOrEmpty(target)
- || !target.Equals(source, StringComparison.Ordinal)))
- {
- targetItem.SetProviderId(provider, source);
- }
+ targetItem.SetProviderId(provider, source);
}
+ }
- private ItemUpdateType SetPeople(MusicAlbum item)
+ private ItemUpdateType SetPeople(MusicAlbum item)
+ {
+ var updateType = ItemUpdateType.None;
+
+ if (item.AlbumArtists.Any() || item.Artists.Any())
{
- var updateType = ItemUpdateType.None;
+ var people = new List<PersonInfo>();
- if (item.AlbumArtists.Any() || item.Artists.Any())
+ foreach (var albumArtist in item.AlbumArtists)
{
- var people = new List<PersonInfo>();
-
- foreach (var albumArtist in item.AlbumArtists)
+ PeopleHelper.AddPerson(people, new PersonInfo
{
- PeopleHelper.AddPerson(people, new PersonInfo
- {
- Name = albumArtist.Trim(),
- Type = PersonKind.AlbumArtist
- });
- }
+ Name = albumArtist.Trim(),
+ Type = PersonKind.AlbumArtist
+ });
+ }
- foreach (var artist in item.Artists)
+ foreach (var artist in item.Artists)
+ {
+ PeopleHelper.AddPerson(people, new PersonInfo
{
- PeopleHelper.AddPerson(people, new PersonInfo
- {
- Name = artist.Trim(),
- Type = PersonKind.Artist
- });
- }
-
- LibraryManager.UpdatePeople(item, people);
- updateType |= ItemUpdateType.MetadataEdit;
+ Name = artist.Trim(),
+ Type = PersonKind.Artist
+ });
}
- return updateType;
+ LibraryManager.UpdatePeople(item, people);
+ updateType |= ItemUpdateType.MetadataEdit;
}
- /// <inheritdoc />
- protected override void MergeData(
- MetadataResult<MusicAlbum> source,
- MetadataResult<MusicAlbum> target,
- MetadataField[] lockedFields,
- bool replaceData,
- bool mergeMetadataSettings)
- {
- base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
+ return updateType;
+ }
- var sourceItem = source.Item;
- var targetItem = target.Item;
+ /// <inheritdoc />
+ protected override void MergeData(
+ MetadataResult<MusicAlbum> source,
+ MetadataResult<MusicAlbum> target,
+ MetadataField[] lockedFields,
+ bool replaceData,
+ bool mergeMetadataSettings)
+ {
+ base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
- if (replaceData || targetItem.Artists.Count == 0)
- {
- targetItem.Artists = sourceItem.Artists;
- }
- else
- {
- targetItem.Artists = targetItem.Artists.Concat(sourceItem.Artists).Distinct().ToArray();
- }
+ var sourceItem = source.Item;
+ var targetItem = target.Item;
- if (replaceData || string.IsNullOrEmpty(targetItem.GetProviderId(MetadataProvider.MusicBrainzAlbumArtist)))
- {
- SetProviderId(sourceItem, targetItem, MetadataProvider.MusicBrainzAlbumArtist);
- }
+ if (replaceData || targetItem.Artists.Count == 0)
+ {
+ targetItem.Artists = sourceItem.Artists;
+ }
+ else
+ {
+ targetItem.Artists = targetItem.Artists.Concat(sourceItem.Artists).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
+ }
- if (replaceData || string.IsNullOrEmpty(targetItem.GetProviderId(MetadataProvider.MusicBrainzAlbum)))
- {
- SetProviderId(sourceItem, targetItem, MetadataProvider.MusicBrainzAlbum);
- }
+ if (replaceData || string.IsNullOrEmpty(targetItem.GetProviderId(MetadataProvider.MusicBrainzAlbumArtist)))
+ {
+ SetProviderId(sourceItem, targetItem, MetadataProvider.MusicBrainzAlbumArtist);
+ }
- if (replaceData || string.IsNullOrEmpty(targetItem.GetProviderId(MetadataProvider.MusicBrainzReleaseGroup)))
- {
- SetProviderId(sourceItem, targetItem, MetadataProvider.MusicBrainzReleaseGroup);
- }
+ if (replaceData || string.IsNullOrEmpty(targetItem.GetProviderId(MetadataProvider.MusicBrainzAlbum)))
+ {
+ SetProviderId(sourceItem, targetItem, MetadataProvider.MusicBrainzAlbum);
+ }
+
+ if (replaceData || string.IsNullOrEmpty(targetItem.GetProviderId(MetadataProvider.MusicBrainzReleaseGroup)))
+ {
+ SetProviderId(sourceItem, targetItem, MetadataProvider.MusicBrainzReleaseGroup);
}
}
}
diff --git a/MediaBrowser.Providers/Music/ArtistMetadataService.cs b/MediaBrowser.Providers/Music/ArtistMetadataService.cs
index c47f9a500..9bac68627 100644
--- a/MediaBrowser.Providers/Music/ArtistMetadataService.cs
+++ b/MediaBrowser.Providers/Music/ArtistMetadataService.cs
@@ -1,43 +1,53 @@
-#pragma warning disable CS1591
-
using System.Collections.Generic;
-using System.Collections.Immutable;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Music
+namespace MediaBrowser.Providers.Music;
+
+/// <summary>
+/// Service to manage artist metadata.
+/// </summary>
+public class ArtistMetadataService : MetadataService<MusicArtist, ArtistInfo>
{
- public class ArtistMetadataService : MetadataService<MusicArtist, ArtistInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ArtistMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public ArtistMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<ArtistMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public ArtistMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<ArtistMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
+ }
- /// <inheritdoc />
- protected override bool EnableUpdatingGenresFromChildren => true;
+ /// <inheritdoc />
+ protected override bool EnableUpdatingGenresFromChildren => true;
- /// <inheritdoc />
- protected override IReadOnlyList<BaseItem> GetChildrenForMetadataUpdates(MusicArtist item)
- {
- return item.IsAccessedByName
- ? item.GetTaggedItems(new InternalItemsQuery
- {
- Recursive = true,
- IsFolder = false
- })
- : item.GetRecursiveChildren(i => i is IHasArtist && !i.IsFolder);
- }
+ /// <inheritdoc />
+ protected override IReadOnlyList<BaseItem> GetChildrenForMetadataUpdates(MusicArtist item)
+ {
+ return item.IsAccessedByName
+ ? item.GetTaggedItems(new InternalItemsQuery
+ {
+ Recursive = true,
+ IsFolder = false
+ })
+ : item.GetRecursiveChildren(i => i is IHasArtist && !i.IsFolder);
}
}
diff --git a/MediaBrowser.Providers/Music/AudioMetadataService.cs b/MediaBrowser.Providers/Music/AudioMetadataService.cs
index 7b25bc0e4..ccc1c90c0 100644
--- a/MediaBrowser.Providers/Music/AudioMetadataService.cs
+++ b/MediaBrowser.Providers/Music/AudioMetadataService.cs
@@ -2,6 +2,7 @@ using System;
using System.Linq;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
@@ -9,71 +10,72 @@ using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Music
+namespace MediaBrowser.Providers.Music;
+
+/// <summary>
+/// The audio metadata service.
+/// </summary>
+public class AudioMetadataService : MetadataService<Audio, SongInfo>
{
/// <summary>
- /// The audio metadata service.
+ /// Initializes a new instance of the <see cref="AudioMetadataService"/> class.
/// </summary>
- public class AudioMetadataService : MetadataService<Audio, SongInfo>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public AudioMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<AudioMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- /// <summary>
- /// Initializes a new instance of the <see cref="AudioMetadataService"/> class.
- /// </summary>
- /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
- /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
- /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
- /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
- /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
- public AudioMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<AudioMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
+ }
- private void SetProviderId(Audio sourceItem, Audio targetItem, bool replaceData, MetadataProvider provider)
+ private void SetProviderId(Audio sourceItem, Audio targetItem, bool replaceData, MetadataProvider provider)
+ {
+ var target = targetItem.GetProviderId(provider);
+ if (replaceData || string.IsNullOrEmpty(target))
{
- var target = targetItem.GetProviderId(provider);
- if (replaceData || string.IsNullOrEmpty(target))
+ var source = sourceItem.GetProviderId(provider);
+ if (!string.IsNullOrEmpty(source)
+ && (string.IsNullOrEmpty(target)
+ || !target.Equals(source, StringComparison.Ordinal)))
{
- var source = sourceItem.GetProviderId(provider);
- if (!string.IsNullOrEmpty(source)
- && (string.IsNullOrEmpty(target)
- || !target.Equals(source, StringComparison.Ordinal)))
- {
- targetItem.SetProviderId(provider, source);
- }
+ targetItem.SetProviderId(provider, source);
}
}
+ }
- /// <inheritdoc />
- protected override void MergeData(MetadataResult<Audio> source, MetadataResult<Audio> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
- {
- base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Audio> source, MetadataResult<Audio> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ {
+ base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
- var sourceItem = source.Item;
- var targetItem = target.Item;
+ var sourceItem = source.Item;
+ var targetItem = target.Item;
- if (replaceData || targetItem.Artists.Count == 0)
- {
- targetItem.Artists = sourceItem.Artists;
- }
- else
- {
- targetItem.Artists = targetItem.Artists.Concat(sourceItem.Artists).Distinct().ToArray();
- }
-
- if (replaceData || string.IsNullOrEmpty(targetItem.Album))
- {
- targetItem.Album = sourceItem.Album;
- }
+ if (replaceData || targetItem.Artists.Count == 0)
+ {
+ targetItem.Artists = sourceItem.Artists;
+ }
+ else
+ {
+ targetItem.Artists = targetItem.Artists.Concat(sourceItem.Artists).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
+ }
- SetProviderId(sourceItem, targetItem, replaceData, MetadataProvider.MusicBrainzAlbumArtist);
- SetProviderId(sourceItem, targetItem, replaceData, MetadataProvider.MusicBrainzAlbum);
- SetProviderId(sourceItem, targetItem, replaceData, MetadataProvider.MusicBrainzReleaseGroup);
+ if (replaceData || string.IsNullOrEmpty(targetItem.Album))
+ {
+ targetItem.Album = sourceItem.Album;
}
+
+ SetProviderId(sourceItem, targetItem, replaceData, MetadataProvider.MusicBrainzAlbumArtist);
+ SetProviderId(sourceItem, targetItem, replaceData, MetadataProvider.MusicBrainzAlbum);
+ SetProviderId(sourceItem, targetItem, replaceData, MetadataProvider.MusicBrainzReleaseGroup);
}
}
diff --git a/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs b/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs
index 24c4b5501..cde14539a 100644
--- a/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs
+++ b/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs
@@ -1,8 +1,8 @@
-#pragma warning disable CS1591
-
+using System;
using System.Linq;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
@@ -10,46 +10,58 @@ using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Music
+namespace MediaBrowser.Providers.Music;
+
+/// <summary>
+/// Service to manage music video metadata.
+/// </summary>
+public class MusicVideoMetadataService : MetadataService<MusicVideo, MusicVideoInfo>
{
- public class MusicVideoMetadataService : MetadataService<MusicVideo, MusicVideoInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MusicVideoMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public MusicVideoMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<MusicVideoMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public MusicVideoMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<MusicVideoMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
+ }
- /// <inheritdoc />
- protected override void MergeData(
- MetadataResult<MusicVideo> source,
- MetadataResult<MusicVideo> target,
- MetadataField[] lockedFields,
- bool replaceData,
- bool mergeMetadataSettings)
- {
- base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
+ /// <inheritdoc />
+ protected override void MergeData(
+ MetadataResult<MusicVideo> source,
+ MetadataResult<MusicVideo> target,
+ MetadataField[] lockedFields,
+ bool replaceData,
+ bool mergeMetadataSettings)
+ {
+ base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
- var sourceItem = source.Item;
- var targetItem = target.Item;
+ var sourceItem = source.Item;
+ var targetItem = target.Item;
- if (replaceData || string.IsNullOrEmpty(targetItem.Album))
- {
- targetItem.Album = sourceItem.Album;
- }
+ if (replaceData || string.IsNullOrEmpty(targetItem.Album))
+ {
+ targetItem.Album = sourceItem.Album;
+ }
- if (replaceData || targetItem.Artists.Count == 0)
- {
- targetItem.Artists = sourceItem.Artists;
- }
- else
- {
- targetItem.Artists = targetItem.Artists.Concat(sourceItem.Artists).Distinct().ToArray();
- }
+ if (replaceData || targetItem.Artists.Count == 0)
+ {
+ targetItem.Artists = sourceItem.Artists;
+ }
+ else
+ {
+ targetItem.Artists = targetItem.Artists.Concat(sourceItem.Artists).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
}
}
}
diff --git a/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs b/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs
index 46eb546c2..201c0efcf 100644
--- a/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs
+++ b/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs
@@ -1,25 +1,36 @@
-#pragma warning disable CS1591
-
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.MusicGenres
+namespace MediaBrowser.Providers.MusicGenres;
+
+/// <summary>
+/// Service to manage music genre metadata.
+/// </summary>
+public class MusicGenreMetadataService : MetadataService<MusicGenre, ItemLookupInfo>
{
- public class MusicGenreMetadataService : MetadataService<MusicGenre, ItemLookupInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MusicGenreMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public MusicGenreMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<MusicGenreMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public MusicGenreMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<MusicGenreMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/People/PersonMetadataService.cs b/MediaBrowser.Providers/People/PersonMetadataService.cs
index 59bf7e4e6..d910327a3 100644
--- a/MediaBrowser.Providers/People/PersonMetadataService.cs
+++ b/MediaBrowser.Providers/People/PersonMetadataService.cs
@@ -1,25 +1,36 @@
-#pragma warning disable CS1591
-
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.People
+namespace MediaBrowser.Providers.People;
+
+/// <summary>
+/// Service to manage person metadata.
+/// </summary>
+public class PersonMetadataService : MetadataService<Person, PersonLookupInfo>
{
- public class PersonMetadataService : MetadataService<Person, PersonLookupInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PersonMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public PersonMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<PersonMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public PersonMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<PersonMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs b/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs
index f2cccb90f..99c2c09c8 100644
--- a/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs
+++ b/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs
@@ -1,25 +1,36 @@
-#pragma warning disable CS1591
-
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Photos
+namespace MediaBrowser.Providers.Photos;
+
+/// <summary>
+/// Service to manage photo album metadata.
+/// </summary>
+public class PhotoAlbumMetadataService : MetadataService<PhotoAlbum, ItemLookupInfo>
{
- public class PhotoAlbumMetadataService : MetadataService<PhotoAlbum, ItemLookupInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PhotoAlbumMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public PhotoAlbumMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<PhotoAlbumMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public PhotoAlbumMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<PhotoAlbumMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/Photos/PhotoMetadataService.cs b/MediaBrowser.Providers/Photos/PhotoMetadataService.cs
index 6941401e0..f90df8406 100644
--- a/MediaBrowser.Providers/Photos/PhotoMetadataService.cs
+++ b/MediaBrowser.Providers/Photos/PhotoMetadataService.cs
@@ -1,25 +1,36 @@
-#pragma warning disable CS1591
-
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Photos
+namespace MediaBrowser.Providers.Photos;
+
+/// <summary>
+/// Service to manage photo metadata.
+/// </summary>
+public class PhotoMetadataService : MetadataService<Photo, ItemLookupInfo>
{
- public class PhotoMetadataService : MetadataService<Photo, ItemLookupInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PhotoMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public PhotoMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<PhotoMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public PhotoMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<PhotoMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs b/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs
index 51a3ba0c7..a986b0b69 100644
--- a/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs
+++ b/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs
@@ -99,7 +99,7 @@ public class PlaylistItemsProvider : ILocalMetadataProvider<Playlist>,
.OfType<CollectionFolder>()
.Where(f => f.CollectionType.HasValue && !_ignoredCollections.Contains(f.CollectionType.Value))
.SelectMany(f => f.PhysicalLocations)
- .Distinct(StringComparer.OrdinalIgnoreCase)
+ .Distinct()
.ToList();
using (var stream = File.OpenRead(path))
diff --git a/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs b/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs
index 7be54453f..b9318f0c8 100644
--- a/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs
+++ b/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs
@@ -1,9 +1,8 @@
-#pragma warning disable CS1591
-
using System.Collections.Generic;
using System.Linq;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Controller.Providers;
@@ -12,62 +11,74 @@ using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Playlists
+namespace MediaBrowser.Providers.Playlists;
+
+/// <summary>
+/// Service to manage playlist metadata.
+/// </summary>
+public class PlaylistMetadataService : MetadataService<Playlist, ItemLookupInfo>
{
- public class PlaylistMetadataService : MetadataService<Playlist, ItemLookupInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PlaylistMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public PlaylistMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<PlaylistMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public PlaylistMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<PlaylistMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
+ }
- /// <inheritdoc />
- protected override bool EnableUpdatingGenresFromChildren => true;
+ /// <inheritdoc />
+ protected override bool EnableUpdatingGenresFromChildren => true;
- /// <inheritdoc />
- protected override bool EnableUpdatingOfficialRatingFromChildren => true;
+ /// <inheritdoc />
+ protected override bool EnableUpdatingOfficialRatingFromChildren => true;
- /// <inheritdoc />
- protected override bool EnableUpdatingStudiosFromChildren => true;
+ /// <inheritdoc />
+ protected override bool EnableUpdatingStudiosFromChildren => true;
- /// <inheritdoc />
- protected override IReadOnlyList<BaseItem> GetChildrenForMetadataUpdates(Playlist item)
- => item.GetLinkedChildren();
+ /// <inheritdoc />
+ protected override IReadOnlyList<BaseItem> GetChildrenForMetadataUpdates(Playlist item)
+ => item.GetLinkedChildren();
- /// <inheritdoc />
- protected override void MergeData(MetadataResult<Playlist> source, MetadataResult<Playlist> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
- {
- base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Playlist> source, MetadataResult<Playlist> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ {
+ base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
- var sourceItem = source.Item;
- var targetItem = target.Item;
+ var sourceItem = source.Item;
+ var targetItem = target.Item;
- if (mergeMetadataSettings)
- {
- targetItem.PlaylistMediaType = sourceItem.PlaylistMediaType;
+ if (mergeMetadataSettings)
+ {
+ targetItem.PlaylistMediaType = sourceItem.PlaylistMediaType;
- if (replaceData || targetItem.LinkedChildren.Length == 0)
- {
- targetItem.LinkedChildren = sourceItem.LinkedChildren;
- }
- else
- {
- targetItem.LinkedChildren = sourceItem.LinkedChildren.Concat(targetItem.LinkedChildren).Distinct().ToArray();
- }
+ if (replaceData || targetItem.LinkedChildren.Length == 0)
+ {
+ targetItem.LinkedChildren = sourceItem.LinkedChildren;
+ }
+ else
+ {
+ targetItem.LinkedChildren = sourceItem.LinkedChildren.Concat(targetItem.LinkedChildren).Distinct().ToArray();
+ }
- if (replaceData || targetItem.Shares.Count == 0)
- {
- targetItem.Shares = sourceItem.Shares;
- }
- else
- {
- targetItem.Shares = sourceItem.Shares.Concat(targetItem.Shares).DistinctBy(s => s.UserId).ToArray();
- }
+ if (replaceData || targetItem.Shares.Count == 0)
+ {
+ targetItem.Shares = sourceItem.Shares;
+ }
+ else
+ {
+ targetItem.Shares = sourceItem.Shares.Concat(targetItem.Shares).DistinctBy(s => s.UserId).ToArray();
}
}
}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs
index 4916a95d9..767004c9e 100644
--- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs
@@ -374,7 +374,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb
/// <returns>The TMDb tv show information.</returns>
public async Task<IReadOnlyList<SearchTv>> SearchSeriesAsync(string name, string language, int year = 0, CancellationToken cancellationToken = default)
{
- var key = $"searchseries-{name}-{language}";
+ var key = $"searchseries-{name}-{year.ToString(CultureInfo.InvariantCulture)}-{language}";
if (_memoryCache.TryGetValue(key, out SearchContainer<SearchTv>? series) && series is not null)
{
return series.Results;
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbExternalUrlProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbExternalUrlProvider.cs
index bec800c03..8d9ec10c1 100644
--- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbExternalUrlProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbExternalUrlProvider.cs
@@ -30,40 +30,43 @@ public class TmdbExternalUrlProvider : IExternalUrlProvider
break;
case Season season:
- if (season.Series.TryGetProviderId(MetadataProvider.Tmdb, out var seriesExternalId))
+ if (season.Series?.TryGetProviderId(MetadataProvider.Tmdb, out var seriesExternalId) == true)
{
var orderString = season.Series.DisplayOrder;
- if (string.IsNullOrEmpty(orderString))
+ var seasonNumber = season.IndexNumber;
+ if (string.IsNullOrEmpty(orderString) && seasonNumber is not null)
{
// Default order is airdate
- yield return TmdbUtils.BaseTmdbUrl + $"tv/{seriesExternalId}/season/{season.IndexNumber}";
+ yield return TmdbUtils.BaseTmdbUrl + $"tv/{seriesExternalId}/season/{seasonNumber}";
}
if (Enum.TryParse<TvGroupType>(season.Series.DisplayOrder, out var order))
{
- if (order.Equals(TvGroupType.OriginalAirDate))
+ if (order.Equals(TvGroupType.OriginalAirDate) && seasonNumber is not null)
{
- yield return TmdbUtils.BaseTmdbUrl + $"tv/{seriesExternalId}/season/{season.IndexNumber}";
+ yield return TmdbUtils.BaseTmdbUrl + $"tv/{seriesExternalId}/season/{seasonNumber}";
}
}
}
break;
case Episode episode:
- if (episode.Series.TryGetProviderId(MetadataProvider.Imdb, out seriesExternalId))
+ if (episode.Series?.TryGetProviderId(MetadataProvider.Tmdb, out seriesExternalId) == true)
{
var orderString = episode.Series.DisplayOrder;
- if (string.IsNullOrEmpty(orderString))
+ var seasonNumber = episode.Season?.IndexNumber;
+ var episodeNumber = episode.IndexNumber;
+ if (string.IsNullOrEmpty(orderString) && seasonNumber is not null && episodeNumber is not null)
{
// Default order is airdate
- yield return TmdbUtils.BaseTmdbUrl + $"tv/{seriesExternalId}/season/{episode.Season.IndexNumber}/episode/{episode.IndexNumber}";
+ yield return TmdbUtils.BaseTmdbUrl + $"tv/{seriesExternalId}/season/{seasonNumber}/episode/{episodeNumber}";
}
if (Enum.TryParse<TvGroupType>(orderString, out var order))
{
- if (order.Equals(TvGroupType.OriginalAirDate))
+ if (order.Equals(TvGroupType.OriginalAirDate) && seasonNumber is not null && episodeNumber is not null)
{
- yield return TmdbUtils.BaseTmdbUrl + $"tv/{seriesExternalId}/season/{episode.Season.IndexNumber}/episode/{episode.IndexNumber}";
+ yield return TmdbUtils.BaseTmdbUrl + $"tv/{seriesExternalId}/season/{seasonNumber}/episode/{episodeNumber}";
}
}
}
diff --git a/MediaBrowser.Providers/Studios/StudioMetadataService.cs b/MediaBrowser.Providers/Studios/StudioMetadataService.cs
index df938325f..d0000442f 100644
--- a/MediaBrowser.Providers/Studios/StudioMetadataService.cs
+++ b/MediaBrowser.Providers/Studios/StudioMetadataService.cs
@@ -1,25 +1,36 @@
-#pragma warning disable CS1591
-
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Studios
+namespace MediaBrowser.Providers.Studios;
+
+/// <summary>
+/// Service to manage studio metadata.
+/// </summary>
+public class StudioMetadataService : MetadataService<Studio, ItemLookupInfo>
{
- public class StudioMetadataService : MetadataService<Studio, ItemLookupInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StudioMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public StudioMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<StudioMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public StudioMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<StudioMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.Providers/TV/EpisodeMetadataService.cs b/MediaBrowser.Providers/TV/EpisodeMetadataService.cs
index 9b4793ee6..b2b6cd9ab 100644
--- a/MediaBrowser.Providers/TV/EpisodeMetadataService.cs
+++ b/MediaBrowser.Providers/TV/EpisodeMetadataService.cs
@@ -1,6 +1,7 @@
using System;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
@@ -8,106 +9,102 @@ using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.TV
+namespace MediaBrowser.Providers.TV;
+
+/// <summary>
+/// Service to manage episode metadata.
+/// </summary>
+public class EpisodeMetadataService : MetadataService<Episode, EpisodeInfo>
{
/// <summary>
- /// Service to manage episode metadata.
+ /// Initializes a new instance of the <see cref="EpisodeMetadataService"/> class.
/// </summary>
- public class EpisodeMetadataService : MetadataService<Episode, EpisodeInfo>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public EpisodeMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<EpisodeMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
+ {
+ }
+
+ /// <inheritdoc />
+ protected override ItemUpdateType BeforeSaveInternal(Episode item, bool isFullRefresh, ItemUpdateType updateType)
{
- /// <summary>
- /// Initializes a new instance of the <see cref="EpisodeMetadataService"/> class.
- /// </summary>
- /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
- /// <param name="logger">Instance of the <see cref="ILogger{SeasonMetadataService}"/> interface.</param>
- /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
- /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
- /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
- public EpisodeMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<EpisodeMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
+ var updatedType = base.BeforeSaveInternal(item, isFullRefresh, updateType);
+
+ var seriesName = item.FindSeriesName();
+ if (!string.Equals(item.SeriesName, seriesName, StringComparison.Ordinal))
{
+ item.SeriesName = seriesName;
+ updatedType |= ItemUpdateType.MetadataImport;
}
- /// <inheritdoc />
- protected override ItemUpdateType BeforeSaveInternal(Episode item, bool isFullRefresh, ItemUpdateType updateType)
+ var seasonName = item.FindSeasonName();
+ if (!string.Equals(item.SeasonName, seasonName, StringComparison.Ordinal))
{
- var updatedType = base.BeforeSaveInternal(item, isFullRefresh, updateType);
-
- var seriesName = item.FindSeriesName();
- if (!string.Equals(item.SeriesName, seriesName, StringComparison.Ordinal))
- {
- item.SeriesName = seriesName;
- updatedType |= ItemUpdateType.MetadataImport;
- }
-
- var seasonName = item.FindSeasonName();
- if (!string.Equals(item.SeasonName, seasonName, StringComparison.Ordinal))
- {
- item.SeasonName = seasonName;
- updatedType |= ItemUpdateType.MetadataImport;
- }
-
- var seriesId = item.FindSeriesId();
- if (!item.SeriesId.Equals(seriesId))
- {
- item.SeriesId = seriesId;
- updatedType |= ItemUpdateType.MetadataImport;
- }
-
- var seasonId = item.FindSeasonId();
- if (!item.SeasonId.Equals(seasonId))
- {
- item.SeasonId = seasonId;
- updatedType |= ItemUpdateType.MetadataImport;
- }
+ item.SeasonName = seasonName;
+ updatedType |= ItemUpdateType.MetadataImport;
+ }
- var seriesPresentationUniqueKey = item.FindSeriesPresentationUniqueKey();
- if (!string.Equals(item.SeriesPresentationUniqueKey, seriesPresentationUniqueKey, StringComparison.Ordinal))
- {
- item.SeriesPresentationUniqueKey = seriesPresentationUniqueKey;
- updatedType |= ItemUpdateType.MetadataImport;
- }
+ var seriesId = item.FindSeriesId();
+ if (!item.SeriesId.Equals(seriesId))
+ {
+ item.SeriesId = seriesId;
+ updatedType |= ItemUpdateType.MetadataImport;
+ }
- return updatedType;
+ var seasonId = item.FindSeasonId();
+ if (!item.SeasonId.Equals(seasonId))
+ {
+ item.SeasonId = seasonId;
+ updatedType |= ItemUpdateType.MetadataImport;
}
- /// <inheritdoc />
- protected override void MergeData(MetadataResult<Episode> source, MetadataResult<Episode> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ var seriesPresentationUniqueKey = item.FindSeriesPresentationUniqueKey();
+ if (!string.Equals(item.SeriesPresentationUniqueKey, seriesPresentationUniqueKey, StringComparison.Ordinal))
{
- base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
+ item.SeriesPresentationUniqueKey = seriesPresentationUniqueKey;
+ updatedType |= ItemUpdateType.MetadataImport;
+ }
+
+ return updatedType;
+ }
- var sourceItem = source.Item;
- var targetItem = target.Item;
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Episode> source, MetadataResult<Episode> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ {
+ base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
- if (replaceData || !targetItem.AirsBeforeSeasonNumber.HasValue)
- {
- targetItem.AirsBeforeSeasonNumber = sourceItem.AirsBeforeSeasonNumber;
- }
+ var sourceItem = source.Item;
+ var targetItem = target.Item;
- if (replaceData || !targetItem.AirsAfterSeasonNumber.HasValue)
- {
- targetItem.AirsAfterSeasonNumber = sourceItem.AirsAfterSeasonNumber;
- }
+ if (replaceData || !targetItem.AirsBeforeSeasonNumber.HasValue)
+ {
+ targetItem.AirsBeforeSeasonNumber = sourceItem.AirsBeforeSeasonNumber;
+ }
- if (replaceData || !targetItem.AirsBeforeEpisodeNumber.HasValue)
- {
- targetItem.AirsBeforeEpisodeNumber = sourceItem.AirsBeforeEpisodeNumber;
- }
+ if (replaceData || !targetItem.AirsAfterSeasonNumber.HasValue)
+ {
+ targetItem.AirsAfterSeasonNumber = sourceItem.AirsAfterSeasonNumber;
+ }
- if (replaceData || !targetItem.IndexNumberEnd.HasValue)
- {
- targetItem.IndexNumberEnd = sourceItem.IndexNumberEnd;
- }
+ if (replaceData || !targetItem.AirsBeforeEpisodeNumber.HasValue)
+ {
+ targetItem.AirsBeforeEpisodeNumber = sourceItem.AirsBeforeEpisodeNumber;
+ }
- if (replaceData || !targetItem.ParentIndexNumber.HasValue)
- {
- targetItem.ParentIndexNumber = sourceItem.ParentIndexNumber;
- }
+ if (replaceData || !targetItem.IndexNumberEnd.HasValue)
+ {
+ targetItem.IndexNumberEnd = sourceItem.IndexNumberEnd;
}
}
}
diff --git a/MediaBrowser.Providers/TV/SeasonMetadataService.cs b/MediaBrowser.Providers/TV/SeasonMetadataService.cs
index b27ccaa6a..ea228a658 100644
--- a/MediaBrowser.Providers/TV/SeasonMetadataService.cs
+++ b/MediaBrowser.Providers/TV/SeasonMetadataService.cs
@@ -4,6 +4,7 @@ using System.Linq;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
@@ -11,102 +12,103 @@ using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.TV
+namespace MediaBrowser.Providers.TV;
+
+/// <summary>
+/// Service to manage season metadata.
+/// </summary>
+public class SeasonMetadataService : MetadataService<Season, SeasonInfo>
{
/// <summary>
- /// Service to manage season metadata.
+ /// Initializes a new instance of the <see cref="SeasonMetadataService"/> class.
/// </summary>
- public class SeasonMetadataService : MetadataService<Season, SeasonInfo>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public SeasonMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<SeasonMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- /// <summary>
- /// Initializes a new instance of the <see cref="SeasonMetadataService"/> class.
- /// </summary>
- /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
- /// <param name="logger">Instance of the <see cref="ILogger{SeasonMetadataService}"/> interface.</param>
- /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
- /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
- /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
- public SeasonMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<SeasonMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
+ }
- /// <inheritdoc />
- protected override bool EnableUpdatingPremiereDateFromChildren => true;
+ /// <inheritdoc />
+ protected override bool EnableUpdatingPremiereDateFromChildren => true;
- /// <inheritdoc />
- protected override ItemUpdateType BeforeSaveInternal(Season item, bool isFullRefresh, ItemUpdateType updateType)
- {
- var updatedType = base.BeforeSaveInternal(item, isFullRefresh, updateType);
-
- if (item.IndexNumber == 0 && !item.IsLocked && !item.LockedFields.Contains(MetadataField.Name))
- {
- var seasonZeroDisplayName = LibraryManager.GetLibraryOptions(item).SeasonZeroDisplayName;
+ /// <inheritdoc />
+ protected override ItemUpdateType BeforeSaveInternal(Season item, bool isFullRefresh, ItemUpdateType updateType)
+ {
+ var updatedType = base.BeforeSaveInternal(item, isFullRefresh, updateType);
- if (!string.Equals(item.Name, seasonZeroDisplayName, StringComparison.OrdinalIgnoreCase))
- {
- item.Name = seasonZeroDisplayName;
- updatedType |= ItemUpdateType.MetadataEdit;
- }
- }
+ if (item.IndexNumber == 0 && !item.IsLocked && !item.LockedFields.Contains(MetadataField.Name))
+ {
+ var seasonZeroDisplayName = LibraryManager.GetLibraryOptions(item).SeasonZeroDisplayName;
- var seriesName = item.FindSeriesName();
- if (!string.Equals(item.SeriesName, seriesName, StringComparison.Ordinal))
+ if (!string.Equals(item.Name, seasonZeroDisplayName, StringComparison.OrdinalIgnoreCase))
{
- item.SeriesName = seriesName;
- updatedType |= ItemUpdateType.MetadataImport;
+ item.Name = seasonZeroDisplayName;
+ updatedType |= ItemUpdateType.MetadataEdit;
}
+ }
- var seriesPresentationUniqueKey = item.FindSeriesPresentationUniqueKey();
- if (!string.Equals(item.SeriesPresentationUniqueKey, seriesPresentationUniqueKey, StringComparison.Ordinal))
- {
- item.SeriesPresentationUniqueKey = seriesPresentationUniqueKey;
- updatedType |= ItemUpdateType.MetadataImport;
- }
+ var seriesName = item.FindSeriesName();
+ if (!string.Equals(item.SeriesName, seriesName, StringComparison.Ordinal))
+ {
+ item.SeriesName = seriesName;
+ updatedType |= ItemUpdateType.MetadataImport;
+ }
- var seriesId = item.FindSeriesId();
- if (!item.SeriesId.Equals(seriesId))
- {
- item.SeriesId = seriesId;
- updatedType |= ItemUpdateType.MetadataImport;
- }
+ var seriesPresentationUniqueKey = item.FindSeriesPresentationUniqueKey();
+ if (!string.Equals(item.SeriesPresentationUniqueKey, seriesPresentationUniqueKey, StringComparison.Ordinal))
+ {
+ item.SeriesPresentationUniqueKey = seriesPresentationUniqueKey;
+ updatedType |= ItemUpdateType.MetadataImport;
+ }
- return updatedType;
+ var seriesId = item.FindSeriesId();
+ if (!item.SeriesId.Equals(seriesId))
+ {
+ item.SeriesId = seriesId;
+ updatedType |= ItemUpdateType.MetadataImport;
}
- /// <inheritdoc />
- protected override IReadOnlyList<BaseItem> GetChildrenForMetadataUpdates(Season item)
- => item.GetEpisodes();
+ return updatedType;
+ }
- /// <inheritdoc />
- protected override ItemUpdateType UpdateMetadataFromChildren(Season item, IReadOnlyList<BaseItem> children, bool isFullRefresh, ItemUpdateType currentUpdateType)
- {
- var updateType = base.UpdateMetadataFromChildren(item, children, isFullRefresh, currentUpdateType);
+ /// <inheritdoc />
+ protected override IReadOnlyList<BaseItem> GetChildrenForMetadataUpdates(Season item)
+ => item.GetEpisodes();
- if (isFullRefresh || currentUpdateType > ItemUpdateType.None)
- {
- updateType |= SaveIsVirtualItem(item, children);
- }
+ /// <inheritdoc />
+ protected override ItemUpdateType UpdateMetadataFromChildren(Season item, IReadOnlyList<BaseItem> children, bool isFullRefresh, ItemUpdateType currentUpdateType)
+ {
+ var updateType = base.UpdateMetadataFromChildren(item, children, isFullRefresh, currentUpdateType);
- return updateType;
+ if (isFullRefresh || currentUpdateType > ItemUpdateType.None)
+ {
+ updateType |= SaveIsVirtualItem(item, children);
}
- private ItemUpdateType SaveIsVirtualItem(Season item, IReadOnlyList<BaseItem> episodes)
- {
- var isVirtualItem = item.LocationType == LocationType.Virtual && (episodes.Count == 0 || episodes.All(i => i.LocationType == LocationType.Virtual));
+ return updateType;
+ }
- if (item.IsVirtualItem != isVirtualItem)
- {
- item.IsVirtualItem = isVirtualItem;
- return ItemUpdateType.MetadataEdit;
- }
+ private ItemUpdateType SaveIsVirtualItem(Season item, IReadOnlyList<BaseItem> episodes)
+ {
+ var isVirtualItem = item.LocationType == LocationType.Virtual && (episodes.Count == 0 || episodes.All(i => i.LocationType == LocationType.Virtual));
- return ItemUpdateType.None;
+ if (item.IsVirtualItem != isVirtualItem)
+ {
+ item.IsVirtualItem = isVirtualItem;
+ return ItemUpdateType.MetadataEdit;
}
+
+ return ItemUpdateType.None;
}
}
diff --git a/MediaBrowser.Providers/TV/SeriesMetadataService.cs b/MediaBrowser.Providers/TV/SeriesMetadataService.cs
index 284415dce..0ccb7f80e 100644
--- a/MediaBrowser.Providers/TV/SeriesMetadataService.cs
+++ b/MediaBrowser.Providers/TV/SeriesMetadataService.cs
@@ -8,6 +8,7 @@ using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
@@ -16,269 +17,270 @@ using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.TV
+namespace MediaBrowser.Providers.TV;
+
+/// <summary>
+/// Service to manage series metadata.
+/// </summary>
+public class SeriesMetadataService : MetadataService<Series, SeriesInfo>
{
+ private readonly ILocalizationManager _localizationManager;
+
/// <summary>
- /// Service to manage series metadata.
+ /// Initializes a new instance of the <see cref="SeriesMetadataService"/> class.
/// </summary>
- public class SeriesMetadataService : MetadataService<Series, SeriesInfo>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="localizationManager">Instance of the <see cref="ILocalizationManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public SeriesMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<SeriesMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ ILocalizationManager localizationManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- private readonly ILocalizationManager _localizationManager;
+ _localizationManager = localizationManager;
+ }
- /// <summary>
- /// Initializes a new instance of the <see cref="SeriesMetadataService"/> class.
- /// </summary>
- /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
- /// <param name="logger">Instance of the <see cref="ILogger{SeasonMetadataService}"/> interface.</param>
- /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
- /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
- /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
- /// <param name="localizationManager">Instance of the <see cref="ILocalizationManager"/> interface.</param>
- public SeriesMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<SeriesMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager,
- ILocalizationManager localizationManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
+ /// <inheritdoc />
+ public override async Task<ItemUpdateType> RefreshMetadata(BaseItem item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken)
+ {
+ if (item is Series series)
{
- _localizationManager = localizationManager;
- }
+ var seasons = series.GetRecursiveChildren(i => i is Season).ToList();
- /// <inheritdoc />
- public override async Task<ItemUpdateType> RefreshMetadata(BaseItem item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken)
- {
- if (item is Series series)
+ foreach (var season in seasons)
{
- var seasons = series.GetRecursiveChildren(i => i is Season).ToList();
-
- foreach (var season in seasons)
+ var hasUpdate = refreshOptions is not null && season.BeforeMetadataRefresh(refreshOptions.ReplaceAllMetadata);
+ if (hasUpdate)
{
- var hasUpdate = refreshOptions != null && season.BeforeMetadataRefresh(refreshOptions.ReplaceAllMetadata);
- if (hasUpdate)
- {
- await season.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false);
- }
+ await season.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false);
}
}
-
- return await base.RefreshMetadata(item, refreshOptions, cancellationToken).ConfigureAwait(false);
}
- /// <inheritdoc />
- protected override async Task AfterMetadataRefresh(Series item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken)
- {
- await base.AfterMetadataRefresh(item, refreshOptions, cancellationToken).ConfigureAwait(false);
+ return await base.RefreshMetadata(item, refreshOptions, cancellationToken).ConfigureAwait(false);
+ }
- RemoveObsoleteEpisodes(item);
- RemoveObsoleteSeasons(item);
- await CreateSeasonsAsync(item, cancellationToken).ConfigureAwait(false);
+ /// <inheritdoc />
+ protected override async Task AfterMetadataRefresh(Series item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken)
+ {
+ await base.AfterMetadataRefresh(item, refreshOptions, cancellationToken).ConfigureAwait(false);
+
+ RemoveObsoleteEpisodes(item);
+ RemoveObsoleteSeasons(item);
+ await CreateSeasonsAsync(item, cancellationToken).ConfigureAwait(false);
+ }
+
+ /// <inheritdoc />
+ protected override void MergeData(MetadataResult<Series> source, MetadataResult<Series> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ {
+ base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
+
+ var sourceItem = source.Item;
+ var targetItem = target.Item;
+
+ if (replaceData || string.IsNullOrEmpty(targetItem.AirTime))
+ {
+ targetItem.AirTime = sourceItem.AirTime;
}
- /// <inheritdoc />
- protected override void MergeData(MetadataResult<Series> source, MetadataResult<Series> target, MetadataField[] lockedFields, bool replaceData, bool mergeMetadataSettings)
+ if (replaceData || !targetItem.Status.HasValue)
{
- base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings);
+ targetItem.Status = sourceItem.Status;
+ }
- var sourceItem = source.Item;
- var targetItem = target.Item;
+ if (replaceData || targetItem.AirDays is null || targetItem.AirDays.Length == 0)
+ {
+ targetItem.AirDays = sourceItem.AirDays;
+ }
+ }
- if (replaceData || string.IsNullOrEmpty(targetItem.AirTime))
+ private void RemoveObsoleteSeasons(Series series)
+ {
+ // TODO Legacy. It's not really "physical" seasons as any virtual seasons are always converted to non-virtual in CreateSeasonsAsync.
+ var physicalSeasonNumbers = new HashSet<int>();
+ var virtualSeasons = new List<Season>();
+ foreach (var existingSeason in series.Children.OfType<Season>())
+ {
+ if (existingSeason.LocationType != LocationType.Virtual && existingSeason.IndexNumber.HasValue)
{
- targetItem.AirTime = sourceItem.AirTime;
+ physicalSeasonNumbers.Add(existingSeason.IndexNumber.Value);
}
-
- if (replaceData || !targetItem.Status.HasValue)
+ else if (existingSeason.LocationType == LocationType.Virtual)
{
- targetItem.Status = sourceItem.Status;
+ virtualSeasons.Add(existingSeason);
}
+ }
- if (replaceData || targetItem.AirDays is null || targetItem.AirDays.Length == 0)
+ foreach (var virtualSeason in virtualSeasons)
+ {
+ var seasonNumber = virtualSeason.IndexNumber;
+ // If there's a physical season with the same number or no episodes in the season, delete it
+ if ((seasonNumber.HasValue && physicalSeasonNumbers.Contains(seasonNumber.Value))
+ || virtualSeason.GetEpisodes().Count == 0)
{
- targetItem.AirDays = sourceItem.AirDays;
+ Logger.LogInformation("Removing virtual season {SeasonNumber} in series {SeriesName}", virtualSeason.IndexNumber, series.Name);
+
+ LibraryManager.DeleteItem(
+ virtualSeason,
+ new DeleteOptions
+ {
+ // Internal metadata paths are removed regardless of this.
+ DeleteFileLocation = false
+ },
+ false);
}
}
+ }
- private void RemoveObsoleteSeasons(Series series)
+ private void RemoveObsoleteEpisodes(Series series)
+ {
+ var episodesBySeason = series.GetEpisodes(null, new DtoOptions(), true)
+ .OfType<Episode>()
+ .GroupBy(e => e.ParentIndexNumber)
+ .ToList();
+
+ foreach (var seasonEpisodes in episodesBySeason)
{
- // TODO Legacy. It's not really "physical" seasons as any virtual seasons are always converted to non-virtual in CreateSeasonsAsync.
- var physicalSeasonNumbers = new HashSet<int>();
- var virtualSeasons = new List<Season>();
- foreach (var existingSeason in series.Children.OfType<Season>())
+ List<Episode> nonPhysicalEpisodes = [];
+ List<Episode> physicalEpisodes = [];
+ foreach (var episode in seasonEpisodes)
{
- if (existingSeason.LocationType != LocationType.Virtual && existingSeason.IndexNumber.HasValue)
+ if (episode.IsVirtualItem || episode.IsMissingEpisode)
{
- physicalSeasonNumbers.Add(existingSeason.IndexNumber.Value);
- }
- else if (existingSeason.LocationType == LocationType.Virtual)
- {
- virtualSeasons.Add(existingSeason);
+ nonPhysicalEpisodes.Add(episode);
+ continue;
}
+
+ physicalEpisodes.Add(episode);
}
- foreach (var virtualSeason in virtualSeasons)
+ // Only consider non-physical episodes
+ foreach (var episode in nonPhysicalEpisodes)
{
- var seasonNumber = virtualSeason.IndexNumber;
- // If there's a physical season with the same number or no episodes in the season, delete it
- if ((seasonNumber.HasValue && physicalSeasonNumbers.Contains(seasonNumber.Value))
- || virtualSeason.GetEpisodes().Count == 0)
- {
- Logger.LogInformation("Removing virtual season {SeasonNumber} in series {SeriesName}", virtualSeason.IndexNumber, series.Name);
+ // Episodes without an episode number are practically orphaned and should be deleted
+ // Episodes with a physical equivalent should be deleted (they are no longer missing)
+ var shouldKeep = episode.IndexNumber.HasValue && !physicalEpisodes.Any(e => e.ContainsEpisodeNumber(episode.IndexNumber.Value));
- LibraryManager.DeleteItem(
- virtualSeason,
- new DeleteOptions
- {
- // Internal metadata paths are removed regardless of this.
- DeleteFileLocation = false
- },
- false);
+ if (shouldKeep)
+ {
+ continue;
}
+
+ DeleteEpisode(episode);
}
}
+ }
- private void RemoveObsoleteEpisodes(Series series)
- {
- var episodesBySeason = series.GetEpisodes(null, new DtoOptions(), true)
- .OfType<Episode>()
- .GroupBy(e => e.ParentIndexNumber)
- .ToList();
+ private void DeleteEpisode(Episode episode)
+ {
+ Logger.LogInformation(
+ "Removing virtual episode S{SeasonNumber}E{EpisodeNumber} in series {SeriesName}",
+ episode.ParentIndexNumber,
+ episode.IndexNumber,
+ episode.SeriesName);
- foreach (var seasonEpisodes in episodesBySeason)
+ LibraryManager.DeleteItem(
+ episode,
+ new DeleteOptions
{
- List<Episode> nonPhysicalEpisodes = [];
- List<Episode> physicalEpisodes = [];
- foreach (var episode in seasonEpisodes)
- {
- if (episode.IsVirtualItem || episode.IsMissingEpisode)
- {
- nonPhysicalEpisodes.Add(episode);
- continue;
- }
+ // Internal metadata paths are removed regardless of this.
+ DeleteFileLocation = false
+ },
+ false);
+ }
- physicalEpisodes.Add(episode);
- }
+ /// <summary>
+ /// Creates seasons for all episodes if they don't exist.
+ /// If no season number can be determined, a dummy season will be created.
+ /// </summary>
+ /// <param name="series">The series.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The async task.</returns>
+ private async Task CreateSeasonsAsync(Series series, CancellationToken cancellationToken)
+ {
+ var seriesChildren = series.GetRecursiveChildren(i => i is Episode || i is Season);
+ var seasons = seriesChildren.OfType<Season>().ToList();
+ var uniqueSeasonNumbers = seriesChildren
+ .OfType<Episode>()
+ .Select(e => e.ParentIndexNumber >= 0 ? e.ParentIndexNumber : null)
+ .Distinct();
- // Only consider non-physical episodes
- foreach (var episode in nonPhysicalEpisodes)
+ // Loop through the unique season numbers
+ foreach (var seasonNumber in uniqueSeasonNumbers)
+ {
+ // Null season numbers will have a 'dummy' season created because seasons are always required.
+ var existingSeason = seasons.FirstOrDefault(i => i.IndexNumber == seasonNumber);
+ if (existingSeason is null)
+ {
+ var seasonName = GetValidSeasonNameForSeries(series, null, seasonNumber);
+ await CreateSeasonAsync(series, seasonName, seasonNumber, cancellationToken).ConfigureAwait(false);
+ }
+ else if (existingSeason.IsVirtualItem)
+ {
+ var episodeCount = seriesChildren.OfType<Episode>().Count(e => e.ParentIndexNumber == seasonNumber && !e.IsMissingEpisode);
+ if (episodeCount > 0)
{
- // Episodes without an episode number are practically orphaned and should be deleted
- // Episodes with a physical equivalent should be deleted (they are no longer missing)
- var shouldKeep = episode.IndexNumber.HasValue && !physicalEpisodes.Any(e => e.ContainsEpisodeNumber(episode.IndexNumber.Value));
-
- if (shouldKeep)
- {
- continue;
- }
-
- DeleteEpisode(episode);
+ existingSeason.IsVirtualItem = false;
+ await existingSeason.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false);
}
}
}
+ }
- private void DeleteEpisode(Episode episode)
- {
- Logger.LogInformation(
- "Removing virtual episode S{SeasonNumber}E{EpisodeNumber} in series {SeriesName}",
- episode.ParentIndexNumber,
- episode.IndexNumber,
- episode.SeriesName);
-
- LibraryManager.DeleteItem(
- episode,
- new DeleteOptions
- {
- // Internal metadata paths are removed regardless of this.
- DeleteFileLocation = false
- },
- false);
- }
+ /// <summary>
+ /// Creates a new season, adds it to the database by linking it to the [series] and refreshes the metadata.
+ /// </summary>
+ /// <param name="series">The series.</param>
+ /// <param name="seasonName">The season name.</param>
+ /// <param name="seasonNumber">The season number.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>The newly created season.</returns>
+ private async Task CreateSeasonAsync(
+ Series series,
+ string? seasonName,
+ int? seasonNumber,
+ CancellationToken cancellationToken)
+ {
+ Logger.LogInformation("Creating Season {SeasonName} entry for {SeriesName}", seasonName, series.Name);
- /// <summary>
- /// Creates seasons for all episodes if they don't exist.
- /// If no season number can be determined, a dummy season will be created.
- /// </summary>
- /// <param name="series">The series.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>The async task.</returns>
- private async Task CreateSeasonsAsync(Series series, CancellationToken cancellationToken)
+ var season = new Season
{
- var seriesChildren = series.GetRecursiveChildren(i => i is Episode || i is Season);
- var seasons = seriesChildren.OfType<Season>().ToList();
- var uniqueSeasonNumbers = seriesChildren
- .OfType<Episode>()
- .Select(e => e.ParentIndexNumber >= 0 ? e.ParentIndexNumber : null)
- .Distinct();
+ Name = seasonName,
+ IndexNumber = seasonNumber,
+ Id = LibraryManager.GetNewItemId(
+ series.Id + (seasonNumber ?? -1).ToString(CultureInfo.InvariantCulture) + seasonName,
+ typeof(Season)),
+ IsVirtualItem = false,
+ SeriesId = series.Id,
+ SeriesName = series.Name,
+ SeriesPresentationUniqueKey = series.GetPresentationUniqueKey()
+ };
- // Loop through the unique season numbers
- foreach (var seasonNumber in uniqueSeasonNumbers)
- {
- // Null season numbers will have a 'dummy' season created because seasons are always required.
- var existingSeason = seasons.FirstOrDefault(i => i.IndexNumber == seasonNumber);
- if (existingSeason is null)
- {
- var seasonName = GetValidSeasonNameForSeries(series, null, seasonNumber);
- await CreateSeasonAsync(series, seasonName, seasonNumber, cancellationToken).ConfigureAwait(false);
- }
- else if (existingSeason.IsVirtualItem)
- {
- var episodeCount = seriesChildren.OfType<Episode>().Count(e => e.ParentIndexNumber == seasonNumber && !e.IsMissingEpisode);
- if (episodeCount > 0)
- {
- existingSeason.IsVirtualItem = false;
- await existingSeason.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false);
- }
- }
- }
- }
+ series.AddChild(season);
+ await season.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken).ConfigureAwait(false);
+ }
- /// <summary>
- /// Creates a new season, adds it to the database by linking it to the [series] and refreshes the metadata.
- /// </summary>
- /// <param name="series">The series.</param>
- /// <param name="seasonName">The season name.</param>
- /// <param name="seasonNumber">The season number.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>The newly created season.</returns>
- private async Task CreateSeasonAsync(
- Series series,
- string? seasonName,
- int? seasonNumber,
- CancellationToken cancellationToken)
+ private string GetValidSeasonNameForSeries(Series series, string? seasonName, int? seasonNumber)
+ {
+ if (string.IsNullOrEmpty(seasonName))
{
- Logger.LogInformation("Creating Season {SeasonName} entry for {SeriesName}", seasonName, series.Name);
-
- var season = new Season
+ seasonName = seasonNumber switch
{
- Name = seasonName,
- IndexNumber = seasonNumber,
- Id = LibraryManager.GetNewItemId(
- series.Id + (seasonNumber ?? -1).ToString(CultureInfo.InvariantCulture) + seasonName,
- typeof(Season)),
- IsVirtualItem = false,
- SeriesId = series.Id,
- SeriesName = series.Name,
- SeriesPresentationUniqueKey = series.GetPresentationUniqueKey()
+ null => _localizationManager.GetLocalizedString("NameSeasonUnknown"),
+ 0 => LibraryManager.GetLibraryOptions(series).SeasonZeroDisplayName,
+ _ => string.Format(CultureInfo.InvariantCulture, _localizationManager.GetLocalizedString("NameSeasonNumber"), seasonNumber.Value)
};
-
- series.AddChild(season);
- await season.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken).ConfigureAwait(false);
}
- private string GetValidSeasonNameForSeries(Series series, string? seasonName, int? seasonNumber)
- {
- if (string.IsNullOrEmpty(seasonName))
- {
- seasonName = seasonNumber switch
- {
- null => _localizationManager.GetLocalizedString("NameSeasonUnknown"),
- 0 => LibraryManager.GetLibraryOptions(series).SeasonZeroDisplayName,
- _ => string.Format(CultureInfo.InvariantCulture, _localizationManager.GetLocalizedString("NameSeasonNumber"), seasonNumber.Value)
- };
- }
-
- return seasonName;
- }
+ return seasonName;
}
}
diff --git a/MediaBrowser.Providers/Trickplay/TrickplayImagesTask.cs b/MediaBrowser.Providers/Trickplay/TrickplayImagesTask.cs
index 4310f93d4..81dcbf893 100644
--- a/MediaBrowser.Providers/Trickplay/TrickplayImagesTask.cs
+++ b/MediaBrowser.Providers/Trickplay/TrickplayImagesTask.cs
@@ -59,14 +59,14 @@ public class TrickplayImagesTask : IScheduledTask
/// <inheritdoc />
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
- return new[]
- {
+ return
+ [
new TaskTriggerInfo
{
Type = TaskTriggerInfoType.DailyTrigger,
TimeOfDayTicks = TimeSpan.FromHours(3).Ticks
}
- };
+ ];
}
/// <inheritdoc />
@@ -74,8 +74,8 @@ public class TrickplayImagesTask : IScheduledTask
{
var query = new InternalItemsQuery
{
- MediaTypes = new[] { MediaType.Video },
- SourceTypes = new[] { SourceType.Library },
+ MediaTypes = [MediaType.Video],
+ SourceTypes = [SourceType.Library],
IsVirtualItem = false,
IsFolder = false,
Recursive = true,
diff --git a/MediaBrowser.Providers/Trickplay/TrickplayProvider.cs b/MediaBrowser.Providers/Trickplay/TrickplayProvider.cs
index 2c74e5f70..768e4617b 100644
--- a/MediaBrowser.Providers/Trickplay/TrickplayProvider.cs
+++ b/MediaBrowser.Providers/Trickplay/TrickplayProvider.cs
@@ -101,7 +101,7 @@ public class TrickplayProvider : ICustomMetadataProvider<Episode>,
bool? enableDuringScan = libraryOptions?.ExtractTrickplayImagesDuringLibraryScan;
bool replace = options.RegenerateTrickplay && options.MetadataRefreshMode > MetadataRefreshMode.Default;
- if (!enableDuringScan.GetValueOrDefault(false))
+ if (libraryOptions is null || !enableDuringScan.GetValueOrDefault(false))
{
return ItemUpdateType.None;
}
diff --git a/MediaBrowser.Providers/Videos/VideoMetadataService.cs b/MediaBrowser.Providers/Videos/VideoMetadataService.cs
index caa6d6e1f..c739bac7d 100644
--- a/MediaBrowser.Providers/Videos/VideoMetadataService.cs
+++ b/MediaBrowser.Providers/Videos/VideoMetadataService.cs
@@ -1,29 +1,40 @@
-#pragma warning disable CS1591
-
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Videos
+namespace MediaBrowser.Providers.Videos;
+
+/// <summary>
+/// Service to manage video metadata.
+/// </summary>
+public class VideoMetadataService : MetadataService<Video, ItemLookupInfo>
{
- public class VideoMetadataService : MetadataService<Video, ItemLookupInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="VideoMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public VideoMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<VideoMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public VideoMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<VideoMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
-
- /// <inheritdoc />
- // Make sure the type-specific services get picked first
- public override int Order => 10;
}
+
+ /// <inheritdoc />
+ // Make sure the type-specific services get picked first
+ public override int Order => 10;
}
diff --git a/MediaBrowser.Providers/Years/YearMetadataService.cs b/MediaBrowser.Providers/Years/YearMetadataService.cs
index 689e8661b..da5f56277 100644
--- a/MediaBrowser.Providers/Years/YearMetadataService.cs
+++ b/MediaBrowser.Providers/Years/YearMetadataService.cs
@@ -1,25 +1,36 @@
-#pragma warning disable CS1591
-
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
using Microsoft.Extensions.Logging;
-namespace MediaBrowser.Providers.Years
+namespace MediaBrowser.Providers.Years;
+
+/// <summary>
+/// Service to manage year metadata.
+/// </summary>
+public class YearMetadataService : MetadataService<Year, ItemLookupInfo>
{
- public class YearMetadataService : MetadataService<Year, ItemLookupInfo>
+ /// <summary>
+ /// Initializes a new instance of the <see cref="YearMetadataService"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param>
+ /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
+ /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+ /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
+ /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+ /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param>
+ public YearMetadataService(
+ IServerConfigurationManager serverConfigurationManager,
+ ILogger<YearMetadataService> logger,
+ IProviderManager providerManager,
+ IFileSystem fileSystem,
+ ILibraryManager libraryManager,
+ IExternalDataManager externalDataManager)
+ : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager)
{
- public YearMetadataService(
- IServerConfigurationManager serverConfigurationManager,
- ILogger<YearMetadataService> logger,
- IProviderManager providerManager,
- IFileSystem fileSystem,
- ILibraryManager libraryManager)
- : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
- {
- }
}
}
diff --git a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs
index 2a1a14834..19b1bbe7b 100644
--- a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs
+++ b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs
@@ -95,7 +95,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers
originalTitle.Append(" / ").Append(additionalEpisode.Item.OriginalTitle);
}
- if (additionalEpisode.Item.IndexNumber != null)
+ if (additionalEpisode.Item.IndexNumber is not null)
{
item.Item.IndexNumberEnd = Math.Max((int)additionalEpisode.Item.IndexNumber, item.Item.IndexNumberEnd ?? (int)additionalEpisode.Item.IndexNumber);
}
diff --git a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs
index 4c8a54cc9..0217bded1 100644
--- a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs
+++ b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs
@@ -1020,12 +1020,12 @@ namespace MediaBrowser.XbmcMetadata.Savers
protected static string SortNameOrName(BaseItem item)
{
- if (item == null)
+ if (item is null)
{
return string.Empty;
}
- if (item.SortName != null)
+ if (item.SortName is not null)
{
string trimmed = item.SortName.Trim();
if (trimmed.Length > 0)
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/DbConfiguration/CustomDatabaseOption.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/DbConfiguration/CustomDatabaseOption.cs
new file mode 100644
index 000000000..fcb8f41b3
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/DbConfiguration/CustomDatabaseOption.cs
@@ -0,0 +1,19 @@
+using System.Collections.Generic;
+
+namespace Jellyfin.Database.Implementations.DbConfiguration;
+
+/// <summary>
+/// The custom value option for custom database providers.
+/// </summary>
+public class CustomDatabaseOption
+{
+ /// <summary>
+ /// Gets or sets the key of the value.
+ /// </summary>
+ public required string Key { get; set; }
+
+ /// <summary>
+ /// Gets or sets the value.
+ /// </summary>
+ public required string Value { get; set; }
+}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/DbConfiguration/CustomDatabaseOptions.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/DbConfiguration/CustomDatabaseOptions.cs
new file mode 100644
index 000000000..e2088704d
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/DbConfiguration/CustomDatabaseOptions.cs
@@ -0,0 +1,32 @@
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+
+namespace Jellyfin.Database.Implementations.DbConfiguration;
+
+/// <summary>
+/// Defines the options for a custom database connector.
+/// </summary>
+public class CustomDatabaseOptions
+{
+ /// <summary>
+ /// Gets or sets the Plugin name to search for database providers.
+ /// </summary>
+ public required string PluginName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the plugin assembly to search for providers.
+ /// </summary>
+ public required string PluginAssembly { get; set; }
+
+ /// <summary>
+ /// Gets or sets the connection string for the custom database provider.
+ /// </summary>
+ public required string ConnectionString { get; set; }
+
+ /// <summary>
+ /// Gets or sets the list of extra options for the custom provider.
+ /// </summary>
+#pragma warning disable CA2227 // Collection properties should be read only
+ public Collection<CustomDatabaseOption> Options { get; set; } = [];
+#pragma warning restore CA2227 // Collection properties should be read only
+}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/DbConfiguration/DatabaseConfigurationOptions.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/DbConfiguration/DatabaseConfigurationOptions.cs
index b481a106f..bc0cacf3c 100644
--- a/src/Jellyfin.Database/Jellyfin.Database.Implementations/DbConfiguration/DatabaseConfigurationOptions.cs
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/DbConfiguration/DatabaseConfigurationOptions.cs
@@ -1,3 +1,5 @@
+using System.Collections.Generic;
+
namespace Jellyfin.Database.Implementations.DbConfiguration;
/// <summary>
@@ -9,4 +11,15 @@ public class DatabaseConfigurationOptions
/// Gets or Sets the type of database jellyfin should use.
/// </summary>
public required string DatabaseType { get; set; }
+
+ /// <summary>
+ /// Gets or sets the options required to use a custom database provider.
+ /// </summary>
+ public CustomDatabaseOptions? CustomProviderOptions { get; set; }
+
+ /// <summary>
+ /// Gets or Sets the kind of locking behavior jellyfin should perform. Possible options are "NoLock", "Pessimistic", "Optimistic".
+ /// Defaults to "NoLock".
+ /// </summary>
+ public DatabaseLockingBehaviorTypes LockingBehavior { get; set; }
}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/DbConfiguration/DatabaseLockingBehaviorTypes.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/DbConfiguration/DatabaseLockingBehaviorTypes.cs
new file mode 100644
index 000000000..3b2a55802
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/DbConfiguration/DatabaseLockingBehaviorTypes.cs
@@ -0,0 +1,22 @@
+namespace Jellyfin.Database.Implementations.DbConfiguration;
+
+/// <summary>
+/// Defines all possible methods for locking database access for concurrent queries.
+/// </summary>
+public enum DatabaseLockingBehaviorTypes
+{
+ /// <summary>
+ /// Defines that no explicit application level locking for reads and writes should be done and only provider specific locking should be relied on.
+ /// </summary>
+ NoLock = 0,
+
+ /// <summary>
+ /// Defines a behavior that always blocks all reads while any one write is done.
+ /// </summary>
+ Pessimistic = 1,
+
+ /// <summary>
+ /// Defines that all writes should be attempted and when fail should be retried.
+ /// </summary>
+ Optimistic = 2
+}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/AttachmentStreamInfo.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/AttachmentStreamInfo.cs
index aab3082b3..2f27d9389 100644
--- a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/AttachmentStreamInfo.cs
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/AttachmentStreamInfo.cs
@@ -25,7 +25,7 @@ public class AttachmentStreamInfo
/// <summary>
/// Gets or Sets the codec of the attachment.
/// </summary>
- public required string Codec { get; set; }
+ public string? Codec { get; set; }
/// <summary>
/// Gets or Sets the codec tag of the attachment.
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/BaseItemEntity.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/BaseItemEntity.cs
index fc9695a09..a09a96317 100644
--- a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/BaseItemEntity.cs
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/BaseItemEntity.cs
@@ -84,6 +84,8 @@ public class BaseItemEntity
public int? InheritedParentalRatingValue { get; set; }
+ public int? InheritedParentalRatingSubValue { get; set; }
+
public string? UnratedType { get; set; }
public float? CriticRating { get; set; }
@@ -162,7 +164,7 @@ public class BaseItemEntity
public ICollection<BaseItemProvider>? Provider { get; set; }
- public ICollection<AncestorId>? ParentAncestors { get; set; }
+ public ICollection<AncestorId>? Parents { get; set; }
public ICollection<AncestorId>? Children { get; set; }
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/KeyframeData.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/KeyframeData.cs
new file mode 100644
index 000000000..c34110c4f
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/KeyframeData.cs
@@ -0,0 +1,32 @@
+#pragma warning disable CA2227 // Collection properties should be read only
+
+using System;
+using System.Collections.Generic;
+
+namespace Jellyfin.Database.Implementations.Entities;
+
+/// <summary>
+/// Keyframe information for a specific file.
+/// </summary>
+public class KeyframeData
+{
+ /// <summary>
+ /// Gets or Sets the ItemId.
+ /// </summary>
+ public required Guid ItemId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the total duration of the stream in ticks.
+ /// </summary>
+ public long TotalDuration { get; set; }
+
+ /// <summary>
+ /// Gets or sets the keyframes in ticks.
+ /// </summary>
+ public ICollection<long>? KeyframeTicks { get; set; }
+
+ /// <summary>
+ /// Gets or sets the item reference.
+ /// </summary>
+ public BaseItemEntity? Item { get; set; }
+}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/MediaStreamInfo.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/MediaStreamInfo.cs
index 207317376..b80b764ba 100644
--- a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/MediaStreamInfo.cs
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/MediaStreamInfo.cs
@@ -99,4 +99,6 @@ public class MediaStreamInfo
public int? Rotation { get; set; }
public string? KeyFrames { get; set; }
+
+ public bool? Hdr10PlusPresentFlag { get; set; }
}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/TrickplayInfo.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/TrickplayInfo.cs
index 06b290e4f..39b449553 100644
--- a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/TrickplayInfo.cs
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/TrickplayInfo.cs
@@ -14,7 +14,6 @@ public class TrickplayInfo
/// <remarks>
/// Required.
/// </remarks>
- [JsonIgnore]
public Guid ItemId { get; set; }
/// <summary>
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/User.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/User.cs
index 31538b5bf..6c81fa729 100644
--- a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/User.cs
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/User.cs
@@ -61,7 +61,6 @@ namespace Jellyfin.Database.Implementations.Entities
/// <remarks>
/// Identity, Indexed, Required.
/// </remarks>
- [JsonIgnore]
public Guid Id { get; set; }
/// <summary>
@@ -249,9 +248,14 @@ namespace Jellyfin.Database.Implementations.Entities
public bool EnableUserPreferenceAccess { get; set; }
/// <summary>
- /// Gets or sets the maximum parental age rating.
+ /// Gets or sets the maximum parental rating score.
/// </summary>
- public int? MaxParentalAgeRating { get; set; }
+ public int? MaxParentalRatingScore { get; set; }
+
+ /// <summary>
+ /// Gets or sets the maximum parental rating sub score.
+ /// </summary>
+ public int? MaxParentalRatingSubScore { get; set; }
/// <summary>
/// Gets or sets the remote client bitrate limit.
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/IJellyfinDatabaseProvider.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/IJellyfinDatabaseProvider.cs
index 566b521dd..6b35810b2 100644
--- a/src/Jellyfin.Database/Jellyfin.Database.Implementations/IJellyfinDatabaseProvider.cs
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/IJellyfinDatabaseProvider.cs
@@ -1,4 +1,5 @@
using System;
+using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
@@ -50,7 +51,7 @@ public interface IJellyfinDatabaseProvider
/// <summary>
/// Runs a full Database backup that can later be restored to.
/// </summary>
- /// <param name="cancellationToken">A cancelation token.</param>
+ /// <param name="cancellationToken">A cancellation token.</param>
/// <returns>A key to identify the backup.</returns>
/// <exception cref="NotImplementedException">May throw an NotImplementException if this operation is not supported for this database.</exception>
Task<string> MigrationBackupFast(CancellationToken cancellationToken);
@@ -59,7 +60,22 @@ public interface IJellyfinDatabaseProvider
/// Restores a backup that has been previously created by <see cref="MigrationBackupFast(CancellationToken)"/>.
/// </summary>
/// <param name="key">The key to the backup from which the current database should be restored from.</param>
- /// <param name="cancellationToken">A cancelation token.</param>
+ /// <param name="cancellationToken">A cancellation token.</param>
/// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
Task RestoreBackupFast(string key, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Deletes a backup that has been previously created by <see cref="MigrationBackupFast(CancellationToken)"/>.
+ /// </summary>
+ /// <param name="key">The key to the backup which should be cleaned up.</param>
+ /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
+ Task DeleteBackup(string key);
+
+ /// <summary>
+ /// Removes all contents from the database.
+ /// </summary>
+ /// <param name="dbContext">The Database context.</param>
+ /// <param name="tableNames">The names of the tables to purge or null for all tables to be purged.</param>
+ /// <returns>A Task.</returns>
+ Task PurgeDatabase(JellyfinDbContext dbContext, IEnumerable<string>? tableNames);
}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Jellyfin.Database.Implementations.csproj b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Jellyfin.Database.Implementations.csproj
index 3b619cce6..28c4972d2 100644
--- a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Jellyfin.Database.Implementations.csproj
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Jellyfin.Database.Implementations.csproj
@@ -10,7 +10,21 @@
<Compile Include="..\..\..\SharedVersion.cs" />
</ItemGroup>
+ <PropertyGroup>
+ <Authors>Jellyfin Contributors</Authors>
+ <PackageId>Jellyfin.Database.Implementations</PackageId>
+ <VersionPrefix>10.11.0</VersionPrefix>
+ <RepositoryUrl>https://github.com/jellyfin/jellyfin</RepositoryUrl>
+ <PackageLicenseExpression>GPL-3.0-only</PackageLicenseExpression>
+ </PropertyGroup>
+
+ <PropertyGroup Condition=" '$(Stability)'=='Unstable'">
+ <!-- Include all symbols in the main nupkg until Azure Artifact Feed starts supporting ingesting NuGet symbol packages. -->
+ <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
+ </PropertyGroup>
+
<ItemGroup>
+ <PackageReference Include="Polly" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design">
<PrivateAssets>all</PrivateAssets>
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/JellyfinDbContext.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/JellyfinDbContext.cs
index 9db70263d..5163bff8b 100644
--- a/src/Jellyfin.Database/Jellyfin.Database.Implementations/JellyfinDbContext.cs
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/JellyfinDbContext.cs
@@ -1,9 +1,14 @@
using System;
+using System.Data.Common;
using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
using Jellyfin.Database.Implementations.Entities;
using Jellyfin.Database.Implementations.Entities.Security;
using Jellyfin.Database.Implementations.Interfaces;
+using Jellyfin.Database.Implementations.Locking;
using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Database.Implementations;
@@ -15,7 +20,8 @@ namespace Jellyfin.Database.Implementations;
/// <param name="options">The database context options.</param>
/// <param name="logger">Logger.</param>
/// <param name="jellyfinDatabaseProvider">The provider for the database engine specific operations.</param>
-public class JellyfinDbContext(DbContextOptions<JellyfinDbContext> options, ILogger<JellyfinDbContext> logger, IJellyfinDatabaseProvider jellyfinDatabaseProvider) : DbContext(options)
+/// <param name="entityFrameworkCoreLocking">The locking behavior.</param>
+public class JellyfinDbContext(DbContextOptions<JellyfinDbContext> options, ILogger<JellyfinDbContext> logger, IJellyfinDatabaseProvider jellyfinDatabaseProvider, IEntityFrameworkCoreLockingBehavior entityFrameworkCoreLocking) : DbContext(options)
{
/// <summary>
/// Gets the <see cref="DbSet{TEntity}"/> containing the access schedules.
@@ -157,6 +163,11 @@ public class JellyfinDbContext(DbContextOptions<JellyfinDbContext> options, ILog
/// </summary>
public DbSet<BaseItemTrailerType> BaseItemTrailerTypes => Set<BaseItemTrailerType>();
+ /// <summary>
+ /// Gets the <see cref="DbSet{TEntity}"/>.
+ /// </summary>
+ public DbSet<KeyframeData> KeyframeData => Set<KeyframeData>();
+
/*public DbSet<Artwork> Artwork => Set<Artwork>();
public DbSet<Book> Books => Set<Book>();
@@ -242,19 +253,41 @@ public class JellyfinDbContext(DbContextOptions<JellyfinDbContext> options, ILog
public DbSet<TrackMetadata> TrackMetadata => Set<TrackMetadata>();*/
/// <inheritdoc/>
- public override int SaveChanges()
+ public override async Task<int> SaveChangesAsync(
+ bool acceptAllChangesOnSuccess,
+ CancellationToken cancellationToken = default)
{
- foreach (var saveEntity in ChangeTracker.Entries()
- .Where(e => e.State == EntityState.Modified)
- .Select(entry => entry.Entity)
- .OfType<IHasConcurrencyToken>())
+ HandleConcurrencyToken();
+
+ try
{
- saveEntity.OnSavingChanges();
+ var result = -1;
+ await entityFrameworkCoreLocking.OnSaveChangesAsync(this, async () =>
+ {
+ result = await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken).ConfigureAwait(false);
+ }).ConfigureAwait(false);
+ return result;
+ }
+ catch (Exception e)
+ {
+ logger.LogError(e, "Error trying to save changes.");
+ throw;
}
+ }
+
+ /// <inheritdoc/>
+ public override int SaveChanges(bool acceptAllChangesOnSuccess) // SaveChanges(bool) is beeing called by SaveChanges() with default to false.
+ {
+ HandleConcurrencyToken();
try
{
- return base.SaveChanges();
+ var result = -1;
+ entityFrameworkCoreLocking.OnSaveChanges(this, () =>
+ {
+ result = base.SaveChanges(acceptAllChangesOnSuccess);
+ });
+ return result;
}
catch (Exception e)
{
@@ -263,6 +296,17 @@ public class JellyfinDbContext(DbContextOptions<JellyfinDbContext> options, ILog
}
}
+ private void HandleConcurrencyToken()
+ {
+ foreach (var saveEntity in ChangeTracker.Entries()
+ .Where(e => e.State == EntityState.Modified)
+ .Select(entry => entry.Entity)
+ .OfType<IHasConcurrencyToken>())
+ {
+ saveEntity.OnSavingChanges();
+ }
+ }
+
/// <inheritdoc />
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/JellyfinQueryHelperExtensions.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/JellyfinQueryHelperExtensions.cs
new file mode 100644
index 000000000..4d5cfb8c9
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/JellyfinQueryHelperExtensions.cs
@@ -0,0 +1,166 @@
+#pragma warning disable RS0030 // Do not use banned APIs
+
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Linq;
+using System.Linq.Expressions;
+using System.Reflection;
+using Jellyfin.Database.Implementations.Entities;
+using Microsoft.EntityFrameworkCore;
+
+namespace Jellyfin.Database.Implementations;
+
+/// <summary>
+/// Contains a number of query related extensions.
+/// </summary>
+public static class JellyfinQueryHelperExtensions
+{
+ private static readonly MethodInfo _containsMethodGenericCache = typeof(Enumerable).GetMethods(BindingFlags.Public | BindingFlags.Static).First(m => m.Name == nameof(Enumerable.Contains) && m.GetParameters().Length == 2);
+ private static readonly MethodInfo _efParameterInstruction = typeof(EF).GetMethod(nameof(EF.Parameter), BindingFlags.Public | BindingFlags.Static)!;
+ private static readonly ConcurrentDictionary<Type, MethodInfo> _containsQueryCache = new();
+
+ /// <summary>
+ /// Builds an optimised query checking one property against a list of values while maintaining an optimal query.
+ /// </summary>
+ /// <typeparam name="TEntity">The entity.</typeparam>
+ /// <typeparam name="TProperty">The property type to compare.</typeparam>
+ /// <param name="query">The source query.</param>
+ /// <param name="oneOf">The list of items to check.</param>
+ /// <param name="property">Property expression.</param>
+ /// <returns>A Query.</returns>
+ public static IQueryable<TEntity> WhereOneOrMany<TEntity, TProperty>(this IQueryable<TEntity> query, IList<TProperty> oneOf, Expression<Func<TEntity, TProperty>> property)
+ {
+ return query.Where(OneOrManyExpressionBuilder(oneOf, property));
+ }
+
+ /// <summary>
+ /// Builds a query that checks referenced ItemValues for a cross BaseItem lookup.
+ /// </summary>
+ /// <param name="baseQuery">The source query.</param>
+ /// <param name="context">The database context.</param>
+ /// <param name="itemValueType">The type of item value to reference.</param>
+ /// <param name="referenceIds">The list of BaseItem ids to check matches.</param>
+ /// <param name="invert">If set an exclusion check is performed instead.</param>
+ /// <returns>A Query.</returns>
+ public static IQueryable<BaseItemEntity> WhereReferencedItem(
+ this IQueryable<BaseItemEntity> baseQuery,
+ JellyfinDbContext context,
+ ItemValueType itemValueType,
+ IList<Guid> referenceIds,
+ bool invert = false)
+ {
+ return baseQuery.Where(ReferencedItemFilterExpressionBuilder(context, itemValueType, referenceIds, invert));
+ }
+
+ /// <summary>
+ /// Builds a query expression that checks referenced ItemValues for a cross BaseItem lookup.
+ /// </summary>
+ /// <param name="context">The database context.</param>
+ /// <param name="itemValueType">The type of item value to reference.</param>
+ /// <param name="referenceIds">The list of BaseItem ids to check matches.</param>
+ /// <param name="invert">If set an exclusion check is performed instead.</param>
+ /// <returns>A Query.</returns>
+ public static Expression<Func<BaseItemEntity, bool>> ReferencedItemFilterExpressionBuilder(
+ this JellyfinDbContext context,
+ ItemValueType itemValueType,
+ IList<Guid> referenceIds,
+ bool invert = false)
+ {
+ // Well genre/artist/album etc items do not actually set the ItemValue of thier specitic types so we cannot match it that way.
+ /*
+ "(guid in (select itemid from ItemValues where CleanValue = (select CleanName from TypedBaseItems where guid=@GenreIds and Type=2)))"
+ */
+
+ var itemFilter = OneOrManyExpressionBuilder<BaseItemEntity, Guid>(referenceIds, f => f.Id);
+
+ return item =>
+ context.ItemValues
+ .Join(context.ItemValuesMap, e => e.ItemValueId, e => e.ItemValueId, (item, map) => new { item, map })
+ .Any(val =>
+ val.item.Type == itemValueType
+ && context.BaseItems.Where(itemFilter).Any(e => e.CleanName == val.item.CleanValue)
+ && val.map.ItemId == item.Id) == EF.Constant(!invert);
+ }
+
+ /// <summary>
+ /// Builds an optimised query expression checking one property against a list of values while maintaining an optimal query.
+ /// </summary>
+ /// <typeparam name="TEntity">The entity.</typeparam>
+ /// <typeparam name="TProperty">The property type to compare.</typeparam>
+ /// <param name="oneOf">The list of items to check.</param>
+ /// <param name="property">Property expression.</param>
+ /// <returns>A Query.</returns>
+ public static Expression<Func<TEntity, bool>> OneOrManyExpressionBuilder<TEntity, TProperty>(this IList<TProperty> oneOf, Expression<Func<TEntity, TProperty>> property)
+ {
+ var parameter = Expression.Parameter(typeof(TEntity), "item");
+ property = ParameterReplacer.Replace<Func<TEntity, TProperty>, Func<TEntity, TProperty>>(property, property.Parameters[0], parameter);
+ if (oneOf.Count == 1)
+ {
+ var value = oneOf[0];
+ if (typeof(TProperty).IsValueType)
+ {
+ return Expression.Lambda<Func<TEntity, bool>>(Expression.Equal(property.Body, Expression.Constant(value)), parameter);
+ }
+ else
+ {
+ return Expression.Lambda<Func<TEntity, bool>>(Expression.ReferenceEqual(property.Body, Expression.Constant(value)), parameter);
+ }
+ }
+
+ var containsMethodInfo = _containsQueryCache.GetOrAdd(typeof(TProperty), static (key) => _containsMethodGenericCache.MakeGenericMethod(key));
+
+ if (oneOf.Count < 4) // arbitrary value choosen.
+ {
+ // if we have 3 or fewer values to check against its faster to do a IN(const,const,const) lookup
+ return Expression.Lambda<Func<TEntity, bool>>(Expression.Call(null, containsMethodInfo, Expression.Constant(oneOf), property.Body), parameter);
+ }
+
+ return Expression.Lambda<Func<TEntity, bool>>(Expression.Call(null, containsMethodInfo, Expression.Call(null, _efParameterInstruction.MakeGenericMethod(oneOf.GetType()), Expression.Constant(oneOf)), property.Body), parameter);
+ }
+
+ internal static class ParameterReplacer
+ {
+ // Produces an expression identical to 'expression'
+ // except with 'source' parameter replaced with 'target' expression.
+ internal static Expression<TOutput> Replace<TInput, TOutput>(
+ Expression<TInput> expression,
+ ParameterExpression source,
+ ParameterExpression target)
+ {
+ return new ParameterReplacerVisitor<TOutput>(source, target)
+ .VisitAndConvert(expression);
+ }
+
+ private sealed class ParameterReplacerVisitor<TOutput> : ExpressionVisitor
+ {
+ private readonly ParameterExpression _source;
+ private readonly ParameterExpression _target;
+
+ public ParameterReplacerVisitor(ParameterExpression source, ParameterExpression target)
+ {
+ _source = source;
+ _target = target;
+ }
+
+ internal Expression<TOutput> VisitAndConvert<T>(Expression<T> root)
+ {
+ return (Expression<TOutput>)VisitLambda(root);
+ }
+
+ protected override Expression VisitLambda<T>(Expression<T> node)
+ {
+ // Leave all parameters alone except the one we want to replace.
+ var parameters = node.Parameters.Select(p => p == _source ? _target : p);
+
+ return Expression.Lambda<TOutput>(Visit(node.Body), parameters);
+ }
+
+ protected override Expression VisitParameter(ParameterExpression node)
+ {
+ // Replace the source with the target, visit other params as usual.
+ return node == _source ? _target : base.VisitParameter(node);
+ }
+ }
+ }
+}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Locking/IEntityFrameworkCoreLockingBehavior.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Locking/IEntityFrameworkCoreLockingBehavior.cs
new file mode 100644
index 000000000..465c31212
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Locking/IEntityFrameworkCoreLockingBehavior.cs
@@ -0,0 +1,32 @@
+using System;
+using System.Threading.Tasks;
+using Microsoft.EntityFrameworkCore;
+
+namespace Jellyfin.Database.Implementations.Locking;
+
+/// <summary>
+/// Defines a jellyfin locking behavior that can be configured.
+/// </summary>
+public interface IEntityFrameworkCoreLockingBehavior
+{
+ /// <summary>
+ /// Provides access to the builder to setup any connection related locking behavior.
+ /// </summary>
+ /// <param name="optionsBuilder">The options builder.</param>
+ void Initialise(DbContextOptionsBuilder optionsBuilder);
+
+ /// <summary>
+ /// Will be invoked when changes should be saved in the current locking behavior.
+ /// </summary>
+ /// <param name="context">The database context invoking the action.</param>
+ /// <param name="saveChanges">Callback for performing the actual save changes.</param>
+ void OnSaveChanges(JellyfinDbContext context, Action saveChanges);
+
+ /// <summary>
+ /// Will be invoked when changes should be saved in the current locking behavior.
+ /// </summary>
+ /// <param name="context">The database context invoking the action.</param>
+ /// <param name="saveChanges">Callback for performing the actual save changes.</param>
+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
+ Task OnSaveChangesAsync(JellyfinDbContext context, Func<Task> saveChanges);
+}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Locking/NoLockBehavior.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Locking/NoLockBehavior.cs
new file mode 100644
index 000000000..3b654f4c4
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Locking/NoLockBehavior.cs
@@ -0,0 +1,41 @@
+using System;
+using System.Threading.Tasks;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Database.Implementations.Locking;
+
+/// <summary>
+/// Default lock behavior. Defines no explicit application locking behavior.
+/// </summary>
+public class NoLockBehavior : IEntityFrameworkCoreLockingBehavior
+{
+ private readonly ILogger<NoLockBehavior> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NoLockBehavior"/> class.
+ /// </summary>
+ /// <param name="logger">The Application logger.</param>
+ public NoLockBehavior(ILogger<NoLockBehavior> logger)
+ {
+ _logger = logger;
+ }
+
+ /// <inheritdoc/>
+ public void OnSaveChanges(JellyfinDbContext context, Action saveChanges)
+ {
+ saveChanges();
+ }
+
+ /// <inheritdoc/>
+ public void Initialise(DbContextOptionsBuilder optionsBuilder)
+ {
+ _logger.LogInformation("The database locking mode has been set to: NoLock.");
+ }
+
+ /// <inheritdoc/>
+ public async Task OnSaveChangesAsync(JellyfinDbContext context, Func<Task> saveChanges)
+ {
+ await saveChanges().ConfigureAwait(false);
+ }
+}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Locking/OptimisticLockBehavior.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Locking/OptimisticLockBehavior.cs
new file mode 100644
index 000000000..9395b2e2d
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Locking/OptimisticLockBehavior.cs
@@ -0,0 +1,137 @@
+using System;
+using System.Data.Common;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Diagnostics;
+using Microsoft.Extensions.Logging;
+using Polly;
+
+namespace Jellyfin.Database.Implementations.Locking;
+
+/// <summary>
+/// Defines a locking mechanism that will retry any write operation for a few times.
+/// </summary>
+public class OptimisticLockBehavior : IEntityFrameworkCoreLockingBehavior
+{
+ private readonly Policy _writePolicy;
+ private readonly AsyncPolicy _writeAsyncPolicy;
+ private readonly ILogger<OptimisticLockBehavior> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OptimisticLockBehavior"/> class.
+ /// </summary>
+ /// <param name="logger">The application logger.</param>
+ public OptimisticLockBehavior(ILogger<OptimisticLockBehavior> logger)
+ {
+ TimeSpan[] sleepDurations = [
+ TimeSpan.FromMilliseconds(50),
+ TimeSpan.FromMilliseconds(50),
+ TimeSpan.FromMilliseconds(250),
+ TimeSpan.FromMilliseconds(150),
+ TimeSpan.FromMilliseconds(500),
+ TimeSpan.FromMilliseconds(500),
+ TimeSpan.FromSeconds(3)
+ ];
+ _logger = logger;
+ _writePolicy = Policy.HandleInner<Exception>(e => e.Message.Contains("database is locked", StringComparison.InvariantCultureIgnoreCase)).WaitAndRetry(sleepDurations, RetryHandle);
+ _writeAsyncPolicy = Policy.HandleInner<Exception>(e => e.Message.Contains("database is locked", StringComparison.InvariantCultureIgnoreCase)).WaitAndRetryAsync(sleepDurations, RetryHandle);
+
+ void RetryHandle(Exception exception, TimeSpan timespan, int retryNo, Context context)
+ {
+ if (retryNo < sleepDurations.Length)
+ {
+ _logger.LogWarning("Operation failed retry {RetryNo}", retryNo);
+ }
+ else
+ {
+ _logger.LogError(exception, "Operation failed retry {RetryNo}", retryNo);
+ }
+ }
+ }
+
+ /// <inheritdoc/>
+ public void Initialise(DbContextOptionsBuilder optionsBuilder)
+ {
+ _logger.LogInformation("The database locking mode has been set to: Optimistic.");
+ optionsBuilder.AddInterceptors(new RetryInterceptor(_writeAsyncPolicy, _writePolicy));
+ optionsBuilder.AddInterceptors(new TransactionLockingInterceptor(_writeAsyncPolicy, _writePolicy));
+ }
+
+ /// <inheritdoc/>
+ public void OnSaveChanges(JellyfinDbContext context, Action saveChanges)
+ {
+ _writePolicy.ExecuteAndCapture(saveChanges);
+ }
+
+ /// <inheritdoc/>
+ public async Task OnSaveChangesAsync(JellyfinDbContext context, Func<Task> saveChanges)
+ {
+ await _writeAsyncPolicy.ExecuteAndCaptureAsync(saveChanges).ConfigureAwait(false);
+ }
+
+ private sealed class TransactionLockingInterceptor : DbTransactionInterceptor
+ {
+ private readonly AsyncPolicy _asyncRetryPolicy;
+ private readonly Policy _retryPolicy;
+
+ public TransactionLockingInterceptor(AsyncPolicy asyncRetryPolicy, Policy retryPolicy)
+ {
+ _asyncRetryPolicy = asyncRetryPolicy;
+ _retryPolicy = retryPolicy;
+ }
+
+ public override InterceptionResult<DbTransaction> TransactionStarting(DbConnection connection, TransactionStartingEventData eventData, InterceptionResult<DbTransaction> result)
+ {
+ return InterceptionResult<DbTransaction>.SuppressWithResult(_retryPolicy.Execute(() => connection.BeginTransaction(eventData.IsolationLevel)));
+ }
+
+ public override async ValueTask<InterceptionResult<DbTransaction>> TransactionStartingAsync(DbConnection connection, TransactionStartingEventData eventData, InterceptionResult<DbTransaction> result, CancellationToken cancellationToken = default)
+ {
+ return InterceptionResult<DbTransaction>.SuppressWithResult(await _asyncRetryPolicy.ExecuteAsync(async () => await connection.BeginTransactionAsync(eventData.IsolationLevel, cancellationToken).ConfigureAwait(false)).ConfigureAwait(false));
+ }
+ }
+
+ private sealed class RetryInterceptor : DbCommandInterceptor
+ {
+ private readonly AsyncPolicy _asyncRetryPolicy;
+ private readonly Policy _retryPolicy;
+
+ public RetryInterceptor(AsyncPolicy asyncRetryPolicy, Policy retryPolicy)
+ {
+ _asyncRetryPolicy = asyncRetryPolicy;
+ _retryPolicy = retryPolicy;
+ }
+
+ public override InterceptionResult<int> NonQueryExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<int> result)
+ {
+ return InterceptionResult<int>.SuppressWithResult(_retryPolicy.Execute(command.ExecuteNonQuery));
+ }
+
+ public override async ValueTask<InterceptionResult<int>> NonQueryExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
+ {
+ return InterceptionResult<int>.SuppressWithResult(await _asyncRetryPolicy.ExecuteAsync(async () => await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false)).ConfigureAwait(false));
+ }
+
+ public override InterceptionResult<object> ScalarExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<object> result)
+ {
+ return InterceptionResult<object>.SuppressWithResult(_retryPolicy.Execute(() => command.ExecuteScalar()!));
+ }
+
+ public override async ValueTask<InterceptionResult<object>> ScalarExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<object> result, CancellationToken cancellationToken = default)
+ {
+ return InterceptionResult<object>.SuppressWithResult((await _asyncRetryPolicy.ExecuteAsync(async () => await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false)!).ConfigureAwait(false))!);
+ }
+
+ public override InterceptionResult<DbDataReader> ReaderExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result)
+ {
+ return InterceptionResult<DbDataReader>.SuppressWithResult(_retryPolicy.Execute(command.ExecuteReader));
+ }
+
+ public override async ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result, CancellationToken cancellationToken = default)
+ {
+ return InterceptionResult<DbDataReader>.SuppressWithResult(await _asyncRetryPolicy.ExecuteAsync(async () => await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false)).ConfigureAwait(false));
+ }
+ }
+}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Locking/PessimisticLockBehavior.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Locking/PessimisticLockBehavior.cs
new file mode 100644
index 000000000..2d6bc6902
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Locking/PessimisticLockBehavior.cs
@@ -0,0 +1,296 @@
+#pragma warning disable MT1013 // Releasing lock without guarantee of execution
+#pragma warning disable MT1012 // Acquiring lock without guarantee of releasing
+
+using System;
+using System.Data;
+using System.Data.Common;
+using System.Runtime.CompilerServices;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Diagnostics;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Database.Implementations.Locking;
+
+/// <summary>
+/// A locking behavior that will always block any operation while a write is requested. Mimicks the old SqliteRepository behavior.
+/// </summary>
+public class PessimisticLockBehavior : IEntityFrameworkCoreLockingBehavior
+{
+ private readonly ILogger<PessimisticLockBehavior> _logger;
+ private readonly ILoggerFactory _loggerFactory;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PessimisticLockBehavior"/> class.
+ /// </summary>
+ /// <param name="logger">The application logger.</param>
+ /// <param name="loggerFactory">The logger factory.</param>
+ public PessimisticLockBehavior(ILogger<PessimisticLockBehavior> logger, ILoggerFactory loggerFactory)
+ {
+ _logger = logger;
+ _loggerFactory = loggerFactory;
+ }
+
+ private static ReaderWriterLockSlim DatabaseLock { get; } = new(LockRecursionPolicy.SupportsRecursion);
+
+ /// <inheritdoc/>
+ public void OnSaveChanges(JellyfinDbContext context, Action saveChanges)
+ {
+ using (DbLock.EnterWrite(_logger))
+ {
+ saveChanges();
+ }
+ }
+
+ /// <inheritdoc/>
+ public void Initialise(DbContextOptionsBuilder optionsBuilder)
+ {
+ _logger.LogInformation("The database locking mode has been set to: Pessimistic.");
+ optionsBuilder.AddInterceptors(new CommandLockingInterceptor(_loggerFactory.CreateLogger<CommandLockingInterceptor>()));
+ optionsBuilder.AddInterceptors(new TransactionLockingInterceptor(_loggerFactory.CreateLogger<TransactionLockingInterceptor>()));
+ }
+
+ /// <inheritdoc/>
+ public async Task OnSaveChangesAsync(JellyfinDbContext context, Func<Task> saveChanges)
+ {
+ using (DbLock.EnterWrite(_logger))
+ {
+ await saveChanges().ConfigureAwait(false);
+ }
+ }
+
+ private sealed class TransactionLockingInterceptor : DbTransactionInterceptor
+ {
+ private readonly ILogger _logger;
+
+ public TransactionLockingInterceptor(ILogger logger)
+ {
+ _logger = logger;
+ }
+
+ public override InterceptionResult<DbTransaction> TransactionStarting(DbConnection connection, TransactionStartingEventData eventData, InterceptionResult<DbTransaction> result)
+ {
+ DbLock.BeginWriteLock(_logger);
+
+ return base.TransactionStarting(connection, eventData, result);
+ }
+
+ public override ValueTask<InterceptionResult<DbTransaction>> TransactionStartingAsync(DbConnection connection, TransactionStartingEventData eventData, InterceptionResult<DbTransaction> result, CancellationToken cancellationToken = default)
+ {
+ DbLock.BeginWriteLock(_logger);
+
+ return base.TransactionStartingAsync(connection, eventData, result, cancellationToken);
+ }
+
+ public override void TransactionCommitted(DbTransaction transaction, TransactionEndEventData eventData)
+ {
+ DbLock.EndWriteLock(_logger);
+
+ base.TransactionCommitted(transaction, eventData);
+ }
+
+ public override Task TransactionCommittedAsync(DbTransaction transaction, TransactionEndEventData eventData, CancellationToken cancellationToken = default)
+ {
+ DbLock.EndWriteLock(_logger);
+
+ return base.TransactionCommittedAsync(transaction, eventData, cancellationToken);
+ }
+
+ public override void TransactionFailed(DbTransaction transaction, TransactionErrorEventData eventData)
+ {
+ DbLock.EndWriteLock(_logger);
+
+ base.TransactionFailed(transaction, eventData);
+ }
+
+ public override Task TransactionFailedAsync(DbTransaction transaction, TransactionErrorEventData eventData, CancellationToken cancellationToken = default)
+ {
+ DbLock.EndWriteLock(_logger);
+
+ return base.TransactionFailedAsync(transaction, eventData, cancellationToken);
+ }
+
+ public override void TransactionRolledBack(DbTransaction transaction, TransactionEndEventData eventData)
+ {
+ DbLock.EndWriteLock(_logger);
+
+ base.TransactionRolledBack(transaction, eventData);
+ }
+
+ public override Task TransactionRolledBackAsync(DbTransaction transaction, TransactionEndEventData eventData, CancellationToken cancellationToken = default)
+ {
+ DbLock.EndWriteLock(_logger);
+
+ return base.TransactionRolledBackAsync(transaction, eventData, cancellationToken);
+ }
+ }
+
+ /// <summary>
+ /// Adds strict read/write locking.
+ /// </summary>
+ private sealed class CommandLockingInterceptor : DbCommandInterceptor
+ {
+ private readonly ILogger _logger;
+
+ public CommandLockingInterceptor(ILogger logger)
+ {
+ _logger = logger;
+ }
+
+ public override InterceptionResult<int> NonQueryExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<int> result)
+ {
+ using (DbLock.EnterWrite(_logger, command))
+ {
+ return InterceptionResult<int>.SuppressWithResult(command.ExecuteNonQuery());
+ }
+ }
+
+ public override async ValueTask<InterceptionResult<int>> NonQueryExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
+ {
+ using (DbLock.EnterWrite(_logger, command))
+ {
+ return InterceptionResult<int>.SuppressWithResult(await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false));
+ }
+ }
+
+ public override InterceptionResult<object> ScalarExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<object> result)
+ {
+ using (DbLock.EnterRead(_logger))
+ {
+ return InterceptionResult<object>.SuppressWithResult(command.ExecuteScalar()!);
+ }
+ }
+
+ public override async ValueTask<InterceptionResult<object>> ScalarExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<object> result, CancellationToken cancellationToken = default)
+ {
+ using (DbLock.EnterRead(_logger))
+ {
+ return InterceptionResult<object>.SuppressWithResult((await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false))!);
+ }
+ }
+
+ public override InterceptionResult<DbDataReader> ReaderExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result)
+ {
+ using (DbLock.EnterRead(_logger))
+ {
+ return InterceptionResult<DbDataReader>.SuppressWithResult(command.ExecuteReader()!);
+ }
+ }
+
+ public override async ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result, CancellationToken cancellationToken = default)
+ {
+ using (DbLock.EnterRead(_logger))
+ {
+ return InterceptionResult<DbDataReader>.SuppressWithResult(await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false));
+ }
+ }
+ }
+
+ private sealed class DbLock : IDisposable
+ {
+ private readonly Action? _action;
+ private bool _disposed;
+
+ private static readonly IDisposable _noLock = new DbLock(null) { _disposed = true };
+ private static (string Command, Guid Id, DateTimeOffset QueryDate, bool Printed) _blockQuery;
+
+ public DbLock(Action? action = null)
+ {
+ _action = action;
+ }
+
+#pragma warning disable IDISP015 // Member should not return created and cached instance
+ public static IDisposable EnterWrite(ILogger logger, IDbCommand? command = null, [CallerMemberName] string? callerMemberName = null, [CallerLineNumber] int? callerNo = null)
+#pragma warning restore IDISP015 // Member should not return created and cached instance
+ {
+ logger.LogTrace("Enter Write for {Caller}:{Line}", callerMemberName, callerNo);
+ if (DatabaseLock.IsWriteLockHeld)
+ {
+ logger.LogTrace("Write Held {Caller}:{Line}", callerMemberName, callerNo);
+ return _noLock;
+ }
+
+ BeginWriteLock(logger, command, callerMemberName, callerNo);
+ return new DbLock(() =>
+ {
+ EndWriteLock(logger, callerMemberName, callerNo);
+ });
+ }
+
+#pragma warning disable IDISP015 // Member should not return created and cached instance
+ public static IDisposable EnterRead(ILogger logger, [CallerMemberName] string? callerMemberName = null, [CallerLineNumber] int? callerNo = null)
+#pragma warning restore IDISP015 // Member should not return created and cached instance
+ {
+ logger.LogTrace("Enter Read {Caller}:{Line}", callerMemberName, callerNo);
+ if (DatabaseLock.IsWriteLockHeld)
+ {
+ logger.LogTrace("Write Held {Caller}:{Line}", callerMemberName, callerNo);
+ return _noLock;
+ }
+
+ BeginReadLock(logger, callerMemberName, callerNo);
+ return new DbLock(() =>
+ {
+ ExitReadLock(logger, callerMemberName, callerNo);
+ });
+ }
+
+ public static void BeginWriteLock(ILogger logger, IDbCommand? command = null, [CallerMemberName] string? callerMemberName = null, [CallerLineNumber] int? callerNo = null)
+ {
+ logger.LogTrace("Aquire Write {Caller}:{Line}", callerMemberName, callerNo);
+ if (!DatabaseLock.TryEnterWriteLock(TimeSpan.FromMilliseconds(1000)))
+ {
+ var blockingQuery = _blockQuery;
+ if (!blockingQuery.Printed)
+ {
+ _blockQuery = (blockingQuery.Command, blockingQuery.Id, blockingQuery.QueryDate, true);
+ logger.LogInformation("QueryLock: {Id} --- {Query}", blockingQuery.Id, blockingQuery.Command);
+ }
+
+ logger.LogInformation("Query congestion detected: '{Id}' since '{Date}'", blockingQuery.Id, blockingQuery.QueryDate);
+
+ DatabaseLock.EnterWriteLock();
+
+ logger.LogInformation("Query congestion cleared: '{Id}' for '{Date}'", blockingQuery.Id, DateTimeOffset.Now - blockingQuery.QueryDate);
+ }
+
+ _blockQuery = (command?.CommandText ?? "Transaction", Guid.NewGuid(), DateTimeOffset.Now, false);
+
+ logger.LogTrace("Write Aquired {Caller}:{Line}", callerMemberName, callerNo);
+ }
+
+ public static void BeginReadLock(ILogger logger, [CallerMemberName] string? callerMemberName = null, [CallerLineNumber] int? callerNo = null)
+ {
+ logger.LogTrace("Aquire Write {Caller}:{Line}", callerMemberName, callerNo);
+ DatabaseLock.EnterReadLock();
+ logger.LogTrace("Read Aquired {Caller}:{Line}", callerMemberName, callerNo);
+ }
+
+ public static void EndWriteLock(ILogger logger, [CallerMemberName] string? callerMemberName = null, [CallerLineNumber] int? callerNo = null)
+ {
+ logger.LogTrace("Release Write {Caller}:{Line}", callerMemberName, callerNo);
+ DatabaseLock.ExitWriteLock();
+ }
+
+ public static void ExitReadLock(ILogger logger, [CallerMemberName] string? callerMemberName = null, [CallerLineNumber] int? callerNo = null)
+ {
+ logger.LogTrace("Release Read {Caller}:{Line}", callerMemberName, callerNo);
+ DatabaseLock.ExitReadLock();
+ }
+
+ public void Dispose()
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ _disposed = true;
+ if (_action is not null)
+ {
+ _action();
+ }
+ }
+ }
+}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/AncestorIdConfiguration.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/AncestorIdConfiguration.cs
index 1cb4a1eb1..67269153d 100644
--- a/src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/AncestorIdConfiguration.cs
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/AncestorIdConfiguration.cs
@@ -14,7 +14,7 @@ public class AncestorIdConfiguration : IEntityTypeConfiguration<AncestorId>
{
builder.HasKey(e => new { e.ItemId, e.ParentItemId });
builder.HasIndex(e => e.ParentItemId);
- builder.HasOne(e => e.ParentItem).WithMany(e => e.ParentAncestors).HasForeignKey(f => f.ParentItemId);
- builder.HasOne(e => e.Item).WithMany(e => e.Children).HasForeignKey(f => f.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.Implementations/ModelConfiguration/BaseItemConfiguration.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/BaseItemConfiguration.cs
index 37816faec..4a76113bf 100644
--- a/src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/BaseItemConfiguration.cs
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/BaseItemConfiguration.cs
@@ -24,7 +24,7 @@ public class BaseItemConfiguration : IEntityTypeConfiguration<BaseItemEntity>
builder.HasMany(e => e.MediaStreams);
builder.HasMany(e => e.Chapters);
builder.HasMany(e => e.Provider);
- builder.HasMany(e => e.ParentAncestors);
+ builder.HasMany(e => e.Parents);
builder.HasMany(e => e.Children);
builder.HasMany(e => e.LockedFields);
builder.HasMany(e => e.TrailerTypes);
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/ItemValuesConfiguration.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/ItemValuesConfiguration.cs
index c8e003eaa..97ebc2e01 100644
--- a/src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/ItemValuesConfiguration.cs
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/ItemValuesConfiguration.cs
@@ -13,6 +13,7 @@ public class ItemValuesConfiguration : IEntityTypeConfiguration<ItemValue>
public void Configure(EntityTypeBuilder<ItemValue> builder)
{
builder.HasKey(e => e.ItemValueId);
- builder.HasIndex(e => new { e.Type, e.CleanValue }).IsUnique();
+ builder.HasIndex(e => new { e.Type, e.CleanValue });
+ builder.HasIndex(e => new { e.Type, e.Value }).IsUnique();
}
}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/KeyframeDataConfiguration.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/KeyframeDataConfiguration.cs
new file mode 100644
index 000000000..3f5d458ca
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/KeyframeDataConfiguration.cs
@@ -0,0 +1,18 @@
+using Jellyfin.Database.Implementations.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace Jellyfin.Database.Implementations.ModelConfiguration;
+
+/// <summary>
+/// KeyframeData Configuration.
+/// </summary>
+public class KeyframeDataConfiguration : IEntityTypeConfiguration<KeyframeData>
+{
+ /// <inheritdoc/>
+ public void Configure(EntityTypeBuilder<KeyframeData> builder)
+ {
+ builder.HasKey(e => e.ItemId);
+ builder.HasOne(e => e.Item).WithMany().HasForeignKey(e => e.ItemId);
+ }
+}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/ProgressablePartitionReporting.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/ProgressablePartitionReporting.cs
new file mode 100644
index 000000000..7654dd3c5
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/ProgressablePartitionReporting.cs
@@ -0,0 +1,55 @@
+using System;
+using System.Diagnostics;
+using System.Linq;
+
+namespace Jellyfin.Database.Implementations;
+
+/// <summary>
+/// Wrapper for progress reporting on Partition helpers.
+/// </summary>
+/// <typeparam name="TEntity">The entity to load.</typeparam>
+public class ProgressablePartitionReporting<TEntity>
+{
+ private readonly IOrderedQueryable<TEntity> _source;
+
+ private readonly Stopwatch _partitionTime = new();
+
+ private readonly Stopwatch _itemTime = new();
+
+ internal ProgressablePartitionReporting(IOrderedQueryable<TEntity> source)
+ {
+ _source = source;
+ }
+
+ internal Action<TEntity, int, int>? OnBeginItem { get; set; }
+
+ internal Action<int>? OnBeginPartition { get; set; }
+
+ internal Action<TEntity, int, int, TimeSpan>? OnEndItem { get; set; }
+
+ internal Action<int, TimeSpan>? OnEndPartition { get; set; }
+
+ internal IOrderedQueryable<TEntity> Source => _source;
+
+ internal void BeginItem(TEntity entity, int iteration, int itemIndex)
+ {
+ _itemTime.Restart();
+ OnBeginItem?.Invoke(entity, iteration, itemIndex);
+ }
+
+ internal void BeginPartition(int iteration)
+ {
+ _partitionTime.Restart();
+ OnBeginPartition?.Invoke(iteration);
+ }
+
+ internal void EndItem(TEntity entity, int iteration, int itemIndex)
+ {
+ OnEndItem?.Invoke(entity, iteration, itemIndex, _itemTime.Elapsed);
+ }
+
+ internal void EndPartition(int iteration)
+ {
+ OnEndPartition?.Invoke(iteration, _partitionTime.Elapsed);
+ }
+}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/QueryPartitionHelpers.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/QueryPartitionHelpers.cs
new file mode 100644
index 000000000..bb66bddca
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/QueryPartitionHelpers.cs
@@ -0,0 +1,215 @@
+using System;
+using System.Buffers;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.EntityFrameworkCore;
+
+namespace Jellyfin.Database.Implementations;
+
+/// <summary>
+/// Contains helpers to partition EFCore queries.
+/// </summary>
+public static class QueryPartitionHelpers
+{
+ /// <summary>
+ /// Adds a callback to any directly following calls of Partition for every partition thats been invoked.
+ /// </summary>
+ /// <typeparam name="TEntity">The entity to load.</typeparam>
+ /// <param name="query">The source query.</param>
+ /// <param name="beginPartition">The callback invoked for partition before enumerating items.</param>
+ /// <param name="endPartition">The callback invoked for partition after enumerating items.</param>
+ /// <returns>A queryable that can be used to partition.</returns>
+ public static ProgressablePartitionReporting<TEntity> WithPartitionProgress<TEntity>(this IOrderedQueryable<TEntity> query, Action<int>? beginPartition = null, Action<int, TimeSpan>? endPartition = null)
+ {
+ var progressable = new ProgressablePartitionReporting<TEntity>(query);
+ progressable.OnBeginPartition = beginPartition;
+ progressable.OnEndPartition = endPartition;
+ return progressable;
+ }
+
+ /// <summary>
+ /// Adds a callback to any directly following calls of Partition for every item thats been invoked.
+ /// </summary>
+ /// <typeparam name="TEntity">The entity to load.</typeparam>
+ /// <param name="query">The source query.</param>
+ /// <param name="beginItem">The callback invoked for each item before processing.</param>
+ /// <param name="endItem">The callback invoked for each item after processing.</param>
+ /// <returns>A queryable that can be used to partition.</returns>
+ public static ProgressablePartitionReporting<TEntity> WithItemProgress<TEntity>(this IOrderedQueryable<TEntity> query, Action<TEntity, int, int>? beginItem = null, Action<TEntity, int, int, TimeSpan>? endItem = null)
+ {
+ var progressable = new ProgressablePartitionReporting<TEntity>(query);
+ progressable.OnBeginItem = beginItem;
+ progressable.OnEndItem = endItem;
+ return progressable;
+ }
+
+ /// <summary>
+ /// Adds a callback to any directly following calls of Partition for every partition thats been invoked.
+ /// </summary>
+ /// <typeparam name="TEntity">The entity to load.</typeparam>
+ /// <param name="progressable">The source query.</param>
+ /// <param name="beginPartition">The callback invoked for partition before enumerating items.</param>
+ /// <param name="endPartition">The callback invoked for partition after enumerating items.</param>
+ /// <returns>A queryable that can be used to partition.</returns>
+ public static ProgressablePartitionReporting<TEntity> WithPartitionProgress<TEntity>(this ProgressablePartitionReporting<TEntity> progressable, Action<int>? beginPartition = null, Action<int, TimeSpan>? endPartition = null)
+ {
+ progressable.OnBeginPartition = beginPartition;
+ progressable.OnEndPartition = endPartition;
+ return progressable;
+ }
+
+ /// <summary>
+ /// Adds a callback to any directly following calls of Partition for every item thats been invoked.
+ /// </summary>
+ /// <typeparam name="TEntity">The entity to load.</typeparam>
+ /// <param name="progressable">The source query.</param>
+ /// <param name="beginItem">The callback invoked for each item before processing.</param>
+ /// <param name="endItem">The callback invoked for each item after processing.</param>
+ /// <returns>A queryable that can be used to partition.</returns>
+ public static ProgressablePartitionReporting<TEntity> WithItemProgress<TEntity>(this ProgressablePartitionReporting<TEntity> progressable, Action<TEntity, int, int>? beginItem = null, Action<TEntity, int, int, TimeSpan>? endItem = null)
+ {
+ progressable.OnBeginItem = beginItem;
+ progressable.OnEndItem = endItem;
+ return progressable;
+ }
+
+ /// <summary>
+ /// Enumerates the source query by loading the entities in partitions in a lazy manner reading each item from the database as its requested.
+ /// </summary>
+ /// <typeparam name="TEntity">The entity to load.</typeparam>
+ /// <param name="partitionInfo">The source query.</param>
+ /// <param name="partitionSize">The number of elements to load per partition.</param>
+ /// <param name="cancellationToken">The cancelation token.</param>
+ /// <returns>A enumerable representing the whole of the query.</returns>
+ public static async IAsyncEnumerable<TEntity> PartitionAsync<TEntity>(this ProgressablePartitionReporting<TEntity> partitionInfo, int partitionSize, [EnumeratorCancellation] CancellationToken cancellationToken = default)
+ {
+ await foreach (var item in partitionInfo.Source.PartitionAsync(partitionSize, partitionInfo, cancellationToken).ConfigureAwait(false))
+ {
+ yield return item;
+ }
+ }
+
+ /// <summary>
+ /// Enumerates the source query by loading the entities in partitions directly into memory.
+ /// </summary>
+ /// <typeparam name="TEntity">The entity to load.</typeparam>
+ /// <param name="partitionInfo">The source query.</param>
+ /// <param name="partitionSize">The number of elements to load per partition.</param>
+ /// <param name="cancellationToken">The cancelation token.</param>
+ /// <returns>A enumerable representing the whole of the query.</returns>
+ public static async IAsyncEnumerable<TEntity> PartitionEagerAsync<TEntity>(this ProgressablePartitionReporting<TEntity> partitionInfo, int partitionSize, [EnumeratorCancellation] CancellationToken cancellationToken = default)
+ {
+ await foreach (var item in partitionInfo.Source.PartitionEagerAsync(partitionSize, partitionInfo, cancellationToken).ConfigureAwait(false))
+ {
+ yield return item;
+ }
+ }
+
+ /// <summary>
+ /// Enumerates the source query by loading the entities in partitions in a lazy manner reading each item from the database as its requested.
+ /// </summary>
+ /// <typeparam name="TEntity">The entity to load.</typeparam>
+ /// <param name="query">The source query.</param>
+ /// <param name="partitionSize">The number of elements to load per partition.</param>
+ /// <param name="progressablePartition">Reporting helper.</param>
+ /// <param name="cancellationToken">The cancelation token.</param>
+ /// <returns>A enumerable representing the whole of the query.</returns>
+ public static async IAsyncEnumerable<TEntity> PartitionAsync<TEntity>(
+ this IOrderedQueryable<TEntity> query,
+ int partitionSize,
+ ProgressablePartitionReporting<TEntity>? progressablePartition = null,
+ [EnumeratorCancellation] CancellationToken cancellationToken = default)
+ {
+ var iterator = 0;
+ int itemCounter;
+ do
+ {
+ progressablePartition?.BeginPartition(iterator);
+ itemCounter = 0;
+ await foreach (var item in query
+ .Skip(partitionSize * iterator)
+ .Take(partitionSize)
+ .AsAsyncEnumerable()
+ .WithCancellation(cancellationToken)
+ .ConfigureAwait(false))
+ {
+ progressablePartition?.BeginItem(item, iterator, itemCounter);
+ yield return item;
+ progressablePartition?.EndItem(item, iterator, itemCounter);
+ itemCounter++;
+ }
+
+ progressablePartition?.EndPartition(iterator);
+ iterator++;
+ } while (itemCounter == partitionSize && !cancellationToken.IsCancellationRequested);
+ }
+
+ /// <summary>
+ /// Enumerates the source query by loading the entities in partitions directly into memory.
+ /// </summary>
+ /// <typeparam name="TEntity">The entity to load.</typeparam>
+ /// <param name="query">The source query.</param>
+ /// <param name="partitionSize">The number of elements to load per partition.</param>
+ /// <param name="progressablePartition">Reporting helper.</param>
+ /// <param name="cancellationToken">The cancelation token.</param>
+ /// <returns>A enumerable representing the whole of the query.</returns>
+ public static async IAsyncEnumerable<TEntity> PartitionEagerAsync<TEntity>(
+ this IOrderedQueryable<TEntity> query,
+ int partitionSize,
+ ProgressablePartitionReporting<TEntity>? progressablePartition = null,
+ [EnumeratorCancellation] CancellationToken cancellationToken = default)
+ {
+ var iterator = 0;
+ int itemCounter;
+ var items = ArrayPool<TEntity>.Shared.Rent(partitionSize);
+ try
+ {
+ do
+ {
+ progressablePartition?.BeginPartition(iterator);
+ itemCounter = 0;
+ await foreach (var item in query
+ .Skip(partitionSize * iterator)
+ .Take(partitionSize)
+ .AsAsyncEnumerable()
+ .WithCancellation(cancellationToken)
+ .ConfigureAwait(false))
+ {
+ items[itemCounter++] = item;
+ }
+
+ for (int i = 0; i < itemCounter; i++)
+ {
+ progressablePartition?.BeginItem(items[i], iterator, itemCounter);
+ yield return items[i];
+ progressablePartition?.EndItem(items[i], iterator, itemCounter);
+ }
+
+ progressablePartition?.EndPartition(iterator);
+ iterator++;
+ } while (itemCounter == partitionSize && !cancellationToken.IsCancellationRequested);
+ }
+ finally
+ {
+ ArrayPool<TEntity>.Shared.Return(items);
+ }
+ }
+
+ /// <summary>
+ /// Adds an Index to the enumeration of the async enumerable.
+ /// </summary>
+ /// <typeparam name="TEntity">The entity to load.</typeparam>
+ /// <param name="query">The source query.</param>
+ /// <returns>The source list with an index added.</returns>
+ public static async IAsyncEnumerable<(TEntity Item, int Index)> WithIndex<TEntity>(this IAsyncEnumerable<TEntity> query)
+ {
+ var index = 0;
+ await foreach (var item in query.ConfigureAwait(false))
+ {
+ yield return (item, index++);
+ }
+ }
+}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250326065026_AddInheritedParentalRatingSubValue.Designer.cs b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250326065026_AddInheritedParentalRatingSubValue.Designer.cs
new file mode 100644
index 000000000..d6befbe5e
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250326065026_AddInheritedParentalRatingSubValue.Designer.cs
@@ -0,0 +1,1658 @@
+// <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.Server.Implementations.Migrations
+{
+ [DbContext(typeof(JellyfinDbContext))]
+ [Migration("20250326065026_AddInheritedParentalRatingSubValue")]
+ partial class AddInheritedParentalRatingSubValue
+ {
+ /// <inheritdoc />
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder.HasAnnotation("ProductVersion", "9.0.3");
+
+ 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");
+
+ 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")
+ .IsRequired()
+ .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<string>("ExtraIds")
+ .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>("OriginalTitle")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Overview")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("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<string>("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("ParentId");
+
+ b.HasIndex("Path");
+
+ b.HasIndex("PresentationUniqueKey");
+
+ b.HasIndex("TopParentId", "Id");
+
+ b.HasIndex("Type", "TopParentId", "Id");
+
+ b.HasIndex("Type", "TopParentId", "PresentationUniqueKey");
+
+ b.HasIndex("Type", "TopParentId", "StartDate");
+
+ b.HasIndex("Id", "Type", "IsFolder", "IsVirtualItem");
+
+ b.HasIndex("MediaType", "TopParentId", "IsVirtualItem", "PresentationUniqueKey");
+
+ b.HasIndex("Type", "SeriesPresentationUniqueKey", "IsFolder", "IsVirtualItem");
+
+ 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);
+ });
+
+ 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");
+
+ 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", "ProviderValue", "ItemId");
+
+ 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")
+ .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.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<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<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("StreamIndex");
+
+ b.HasIndex("StreamType");
+
+ b.HasIndex("StreamIndex", "StreamType");
+
+ b.HasIndex("StreamIndex", "StreamType", "Language");
+
+ 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<int?>("ListOrder")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Role")
+ .HasColumnType("TEXT");
+
+ b.Property<int?>("SortOrder")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("ItemId", "PeopleId");
+
+ b.HasIndex("PeopleId");
+
+ b.HasIndex("ItemId", "ListOrder");
+
+ b.HasIndex("ItemId", "SortOrder");
+
+ 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<Guid?>("Permission_Permissions_Guid")
+ .HasColumnType("TEXT");
+
+ 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()
+ .HasFilter("[UserId] IS NOT NULL");
+
+ 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<Guid?>("Preference_Preferences_Guid")
+ .HasColumnType("TEXT");
+
+ 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()
+ .HasFilter("[UserId] IS NOT NULL");
+
+ 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("DeviceId");
+
+ 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>("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("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<int?>("SubtitleStreamIndex")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("ItemId", "UserId", "CustomDataKey");
+
+ b.HasIndex("UserId");
+
+ b.HasIndex("ItemId", "UserId", "IsFavorite");
+
+ b.HasIndex("ItemId", "UserId", "LastPlayedDate");
+
+ b.HasIndex("ItemId", "UserId", "PlaybackPositionTicks");
+
+ b.HasIndex("ItemId", "UserId", "Played");
+
+ 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("Children")
+ .HasForeignKey("ItemId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "ParentItem")
+ .WithMany("ParentAncestors")
+ .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.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.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);
+ });
+
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Preference", b =>
+ {
+ b.HasOne("Jellyfin.Database.Implementations.Entities.User", null)
+ .WithMany("Preferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade);
+ });
+
+ 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("Images");
+
+ b.Navigation("ItemValues");
+
+ b.Navigation("LockedFields");
+
+ b.Navigation("MediaStreams");
+
+ b.Navigation("ParentAncestors");
+
+ 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/20250326065026_AddInheritedParentalRatingSubValue.cs b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250326065026_AddInheritedParentalRatingSubValue.cs
new file mode 100644
index 000000000..71f56a149
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250326065026_AddInheritedParentalRatingSubValue.cs
@@ -0,0 +1,48 @@
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ /// <inheritdoc />
+ public partial class AddInheritedParentalRatingSubValue : Migration
+ {
+ /// <inheritdoc />
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.RenameColumn(
+ name: "MaxParentalAgeRating",
+ table: "Users",
+ newName: "MaxParentalRatingScore");
+
+ migrationBuilder.AddColumn<int>(
+ name: "MaxParentalRatingSubScore",
+ table: "Users",
+ type: "INTEGER",
+ nullable: true);
+
+ migrationBuilder.AddColumn<int>(
+ name: "InheritedParentalRatingSubValue",
+ table: "BaseItems",
+ type: "INTEGER",
+ nullable: true);
+ }
+
+ /// <inheritdoc />
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropColumn(
+ name: "MaxParentalRatingSubScore",
+ table: "Users");
+
+ migrationBuilder.DropColumn(
+ name: "InheritedParentalRatingValue",
+ table: "BaseItems");
+
+ migrationBuilder.RenameColumn(
+ name: "MaxParentalRatingScore",
+ table: "Users",
+ newName: "MaxParentalAgeRating");
+ }
+ }
+}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250327101120_AddKeyframeData.Designer.cs b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250327101120_AddKeyframeData.Designer.cs
new file mode 100644
index 000000000..434ea820a
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250327101120_AddKeyframeData.Designer.cs
@@ -0,0 +1,1681 @@
+// <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.Server.Implementations.Migrations
+{
+ [DbContext(typeof(JellyfinDbContext))]
+ [Migration("20250327101120_AddKeyframeData")]
+ partial class AddKeyframeData
+ {
+ /// <inheritdoc />
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder.HasAnnotation("ProductVersion", "9.0.3");
+
+ 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");
+
+ 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")
+ .IsRequired()
+ .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<string>("ExtraIds")
+ .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?>("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>("OriginalTitle")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Overview")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("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<string>("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("ParentId");
+
+ b.HasIndex("Path");
+
+ b.HasIndex("PresentationUniqueKey");
+
+ b.HasIndex("TopParentId", "Id");
+
+ b.HasIndex("Type", "TopParentId", "Id");
+
+ b.HasIndex("Type", "TopParentId", "PresentationUniqueKey");
+
+ b.HasIndex("Type", "TopParentId", "StartDate");
+
+ b.HasIndex("Id", "Type", "IsFolder", "IsVirtualItem");
+
+ b.HasIndex("MediaType", "TopParentId", "IsVirtualItem", "PresentationUniqueKey");
+
+ b.HasIndex("Type", "SeriesPresentationUniqueKey", "IsFolder", "IsVirtualItem");
+
+ 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);
+ });
+
+ 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");
+
+ 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", "ProviderValue", "ItemId");
+
+ 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")
+ .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.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<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<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("StreamIndex");
+
+ b.HasIndex("StreamType");
+
+ b.HasIndex("StreamIndex", "StreamType");
+
+ b.HasIndex("StreamIndex", "StreamType", "Language");
+
+ 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<int?>("ListOrder")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Role")
+ .HasColumnType("TEXT");
+
+ b.Property<int?>("SortOrder")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("ItemId", "PeopleId");
+
+ b.HasIndex("PeopleId");
+
+ b.HasIndex("ItemId", "ListOrder");
+
+ b.HasIndex("ItemId", "SortOrder");
+
+ 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<Guid?>("Permission_Permissions_Guid")
+ .HasColumnType("TEXT");
+
+ 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()
+ .HasFilter("[UserId] IS NOT NULL");
+
+ 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<Guid?>("Preference_Preferences_Guid")
+ .HasColumnType("TEXT");
+
+ 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()
+ .HasFilter("[UserId] IS NOT NULL");
+
+ 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("DeviceId");
+
+ 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?>("MaxParentalAgeRating")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("MustUpdatePassword")
+ .HasColumnType("INTEGER");
+
+ 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("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<int?>("SubtitleStreamIndex")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("ItemId", "UserId", "CustomDataKey");
+
+ b.HasIndex("UserId");
+
+ b.HasIndex("ItemId", "UserId", "IsFavorite");
+
+ b.HasIndex("ItemId", "UserId", "LastPlayedDate");
+
+ b.HasIndex("ItemId", "UserId", "PlaybackPositionTicks");
+
+ b.HasIndex("ItemId", "UserId", "Played");
+
+ 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("Children")
+ .HasForeignKey("ItemId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "ParentItem")
+ .WithMany("ParentAncestors")
+ .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.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.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);
+ });
+
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Preference", b =>
+ {
+ b.HasOne("Jellyfin.Database.Implementations.Entities.User", null)
+ .WithMany("Preferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade);
+ });
+
+ 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("Images");
+
+ b.Navigation("ItemValues");
+
+ b.Navigation("LockedFields");
+
+ b.Navigation("MediaStreams");
+
+ b.Navigation("ParentAncestors");
+
+ 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/20250327101120_AddKeyframeData.cs b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250327101120_AddKeyframeData.cs
new file mode 100644
index 000000000..c17b35b40
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250327101120_AddKeyframeData.cs
@@ -0,0 +1,41 @@
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ /// <inheritdoc />
+ public partial class AddKeyframeData : Migration
+ {
+ /// <inheritdoc />
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateTable(
+ name: "KeyframeData",
+ columns: table => new
+ {
+ ItemId = table.Column<Guid>(type: "TEXT", nullable: false),
+ TotalDuration = table.Column<long>(type: "INTEGER", nullable: false),
+ KeyframeTicks = table.Column<string>(type: "TEXT", nullable: true)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_KeyframeData", x => x.ItemId);
+ table.ForeignKey(
+ name: "FK_KeyframeData_BaseItems_ItemId",
+ column: x => x.ItemId,
+ principalTable: "BaseItems",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+ });
+ }
+
+ /// <inheritdoc />
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "KeyframeData");
+ }
+ }
+}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250327171413_AddHdr10PlusFlag.Designer.cs b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250327171413_AddHdr10PlusFlag.Designer.cs
new file mode 100644
index 000000000..bad01778d
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250327171413_AddHdr10PlusFlag.Designer.cs
@@ -0,0 +1,1655 @@
+// <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.Server.Implementations.Migrations
+{
+ [DbContext(typeof(JellyfinDbContext))]
+ [Migration("20250327171413_AddHdr10PlusFlag")]
+ partial class AddHdr10PlusFlag
+ {
+ /// <inheritdoc />
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder.HasAnnotation("ProductVersion", "9.0.3");
+
+ 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");
+
+ 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")
+ .IsRequired()
+ .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<string>("ExtraIds")
+ .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?>("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>("OriginalTitle")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Overview")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("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<string>("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("ParentId");
+
+ b.HasIndex("Path");
+
+ b.HasIndex("PresentationUniqueKey");
+
+ b.HasIndex("TopParentId", "Id");
+
+ b.HasIndex("Type", "TopParentId", "Id");
+
+ b.HasIndex("Type", "TopParentId", "PresentationUniqueKey");
+
+ b.HasIndex("Type", "TopParentId", "StartDate");
+
+ b.HasIndex("Id", "Type", "IsFolder", "IsVirtualItem");
+
+ b.HasIndex("MediaType", "TopParentId", "IsVirtualItem", "PresentationUniqueKey");
+
+ b.HasIndex("Type", "SeriesPresentationUniqueKey", "IsFolder", "IsVirtualItem");
+
+ 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);
+ });
+
+ 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");
+
+ 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", "ProviderValue", "ItemId");
+
+ 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")
+ .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.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<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("StreamIndex");
+
+ b.HasIndex("StreamType");
+
+ b.HasIndex("StreamIndex", "StreamType");
+
+ b.HasIndex("StreamIndex", "StreamType", "Language");
+
+ 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<int?>("ListOrder")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Role")
+ .HasColumnType("TEXT");
+
+ b.Property<int?>("SortOrder")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("ItemId", "PeopleId");
+
+ b.HasIndex("PeopleId");
+
+ b.HasIndex("ItemId", "ListOrder");
+
+ b.HasIndex("ItemId", "SortOrder");
+
+ 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<Guid?>("Permission_Permissions_Guid")
+ .HasColumnType("TEXT");
+
+ 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()
+ .HasFilter("[UserId] IS NOT NULL");
+
+ 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<Guid?>("Preference_Preferences_Guid")
+ .HasColumnType("TEXT");
+
+ 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()
+ .HasFilter("[UserId] IS NOT NULL");
+
+ 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("DeviceId");
+
+ 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?>("MaxParentalAgeRating")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("MustUpdatePassword")
+ .HasColumnType("INTEGER");
+
+ 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("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<int?>("SubtitleStreamIndex")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("ItemId", "UserId", "CustomDataKey");
+
+ b.HasIndex("UserId");
+
+ b.HasIndex("ItemId", "UserId", "IsFavorite");
+
+ b.HasIndex("ItemId", "UserId", "LastPlayedDate");
+
+ b.HasIndex("ItemId", "UserId", "PlaybackPositionTicks");
+
+ b.HasIndex("ItemId", "UserId", "Played");
+
+ 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("Children")
+ .HasForeignKey("ItemId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "ParentItem")
+ .WithMany("ParentAncestors")
+ .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.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.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);
+ });
+
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Preference", b =>
+ {
+ b.HasOne("Jellyfin.Database.Implementations.Entities.User", null)
+ .WithMany("Preferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade);
+ });
+
+ 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("Images");
+
+ b.Navigation("ItemValues");
+
+ b.Navigation("LockedFields");
+
+ b.Navigation("MediaStreams");
+
+ b.Navigation("ParentAncestors");
+
+ 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/20250327171413_AddHdr10PlusFlag.cs b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250327171413_AddHdr10PlusFlag.cs
new file mode 100644
index 000000000..5766cd382
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250327171413_AddHdr10PlusFlag.cs
@@ -0,0 +1,28 @@
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ /// <inheritdoc />
+ public partial class AddHdr10PlusFlag : Migration
+ {
+ /// <inheritdoc />
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AddColumn<bool>(
+ name: "Hdr10PlusPresentFlag",
+ table: "MediaStreamInfos",
+ type: "INTEGER",
+ nullable: true);
+ }
+
+ /// <inheritdoc />
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropColumn(
+ name: "Hdr10PlusPresentFlag",
+ table: "MediaStreamInfos");
+ }
+ }
+}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250331182844_FixAttachmentMigration.Designer.cs b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250331182844_FixAttachmentMigration.Designer.cs
new file mode 100644
index 000000000..d668eea92
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250331182844_FixAttachmentMigration.Designer.cs
@@ -0,0 +1,1657 @@
+// <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.Server.Implementations.Migrations
+{
+ [DbContext(typeof(JellyfinDbContext))]
+ [Migration("20250331182844_FixAttachmentMigration")]
+ partial class FixAttachmentMigration
+ {
+ /// <inheritdoc />
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder.HasAnnotation("ProductVersion", "9.0.3");
+
+ 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");
+
+ 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<string>("ExtraIds")
+ .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>("OriginalTitle")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Overview")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("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<string>("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("ParentId");
+
+ b.HasIndex("Path");
+
+ b.HasIndex("PresentationUniqueKey");
+
+ b.HasIndex("TopParentId", "Id");
+
+ b.HasIndex("Type", "TopParentId", "Id");
+
+ b.HasIndex("Type", "TopParentId", "PresentationUniqueKey");
+
+ b.HasIndex("Type", "TopParentId", "StartDate");
+
+ b.HasIndex("Id", "Type", "IsFolder", "IsVirtualItem");
+
+ b.HasIndex("MediaType", "TopParentId", "IsVirtualItem", "PresentationUniqueKey");
+
+ b.HasIndex("Type", "SeriesPresentationUniqueKey", "IsFolder", "IsVirtualItem");
+
+ 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);
+ });
+
+ 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");
+
+ 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", "ProviderValue", "ItemId");
+
+ 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")
+ .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.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<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<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("StreamIndex");
+
+ b.HasIndex("StreamType");
+
+ b.HasIndex("StreamIndex", "StreamType");
+
+ b.HasIndex("StreamIndex", "StreamType", "Language");
+
+ 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<int?>("ListOrder")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Role")
+ .HasColumnType("TEXT");
+
+ b.Property<int?>("SortOrder")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("ItemId", "PeopleId");
+
+ b.HasIndex("PeopleId");
+
+ b.HasIndex("ItemId", "ListOrder");
+
+ b.HasIndex("ItemId", "SortOrder");
+
+ 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<Guid?>("Permission_Permissions_Guid")
+ .HasColumnType("TEXT");
+
+ 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()
+ .HasFilter("[UserId] IS NOT NULL");
+
+ 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<Guid?>("Preference_Preferences_Guid")
+ .HasColumnType("TEXT");
+
+ 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()
+ .HasFilter("[UserId] IS NOT NULL");
+
+ 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("DeviceId");
+
+ 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>("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("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<int?>("SubtitleStreamIndex")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("ItemId", "UserId", "CustomDataKey");
+
+ b.HasIndex("UserId");
+
+ b.HasIndex("ItemId", "UserId", "IsFavorite");
+
+ b.HasIndex("ItemId", "UserId", "LastPlayedDate");
+
+ b.HasIndex("ItemId", "UserId", "PlaybackPositionTicks");
+
+ b.HasIndex("ItemId", "UserId", "Played");
+
+ 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("Children")
+ .HasForeignKey("ItemId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "ParentItem")
+ .WithMany("ParentAncestors")
+ .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.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.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);
+ });
+
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Preference", b =>
+ {
+ b.HasOne("Jellyfin.Database.Implementations.Entities.User", null)
+ .WithMany("Preferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade);
+ });
+
+ 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("Images");
+
+ b.Navigation("ItemValues");
+
+ b.Navigation("LockedFields");
+
+ b.Navigation("MediaStreams");
+
+ b.Navigation("ParentAncestors");
+
+ 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/20250331182844_FixAttachmentMigration.cs b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250331182844_FixAttachmentMigration.cs
new file mode 100644
index 000000000..f921856a2
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250331182844_FixAttachmentMigration.cs
@@ -0,0 +1,36 @@
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ /// <inheritdoc />
+ public partial class FixAttachmentMigration : Migration
+ {
+ /// <inheritdoc />
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AlterColumn<string>(
+ name: "Codec",
+ table: "AttachmentStreamInfos",
+ type: "TEXT",
+ nullable: true,
+ oldClrType: typeof(string),
+ oldType: "TEXT");
+ }
+
+ /// <inheritdoc />
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AlterColumn<string>(
+ name: "Codec",
+ table: "AttachmentStreamInfos",
+ type: "TEXT",
+ nullable: false,
+ defaultValue: string.Empty,
+ oldClrType: typeof(string),
+ oldType: "TEXT",
+ oldNullable: true);
+ }
+ }
+}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250401142247_FixAncestors.Designer.cs b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250401142247_FixAncestors.Designer.cs
new file mode 100644
index 000000000..d7672b137
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250401142247_FixAncestors.Designer.cs
@@ -0,0 +1,1658 @@
+// <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.Server.Implementations.Migrations
+{
+ [DbContext(typeof(JellyfinDbContext))]
+ [Migration("20250401142247_FixAncestors")]
+ partial class FixAncestors
+ {
+ /// <inheritdoc />
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder.HasAnnotation("ProductVersion", "9.0.3");
+
+ 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");
+
+ 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")
+ .IsRequired()
+ .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<string>("ExtraIds")
+ .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>("OriginalTitle")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Overview")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("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<string>("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("ParentId");
+
+ b.HasIndex("Path");
+
+ b.HasIndex("PresentationUniqueKey");
+
+ b.HasIndex("TopParentId", "Id");
+
+ b.HasIndex("Type", "TopParentId", "Id");
+
+ b.HasIndex("Type", "TopParentId", "PresentationUniqueKey");
+
+ b.HasIndex("Type", "TopParentId", "StartDate");
+
+ b.HasIndex("Id", "Type", "IsFolder", "IsVirtualItem");
+
+ b.HasIndex("MediaType", "TopParentId", "IsVirtualItem", "PresentationUniqueKey");
+
+ b.HasIndex("Type", "SeriesPresentationUniqueKey", "IsFolder", "IsVirtualItem");
+
+ 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);
+ });
+
+ 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");
+
+ 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", "ProviderValue", "ItemId");
+
+ 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")
+ .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.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<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<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("StreamIndex");
+
+ b.HasIndex("StreamType");
+
+ b.HasIndex("StreamIndex", "StreamType");
+
+ b.HasIndex("StreamIndex", "StreamType", "Language");
+
+ 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<int?>("ListOrder")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Role")
+ .HasColumnType("TEXT");
+
+ b.Property<int?>("SortOrder")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("ItemId", "PeopleId");
+
+ b.HasIndex("PeopleId");
+
+ b.HasIndex("ItemId", "ListOrder");
+
+ b.HasIndex("ItemId", "SortOrder");
+
+ 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<Guid?>("Permission_Permissions_Guid")
+ .HasColumnType("TEXT");
+
+ 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()
+ .HasFilter("[UserId] IS NOT NULL");
+
+ 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<Guid?>("Preference_Preferences_Guid")
+ .HasColumnType("TEXT");
+
+ 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()
+ .HasFilter("[UserId] IS NOT NULL");
+
+ 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("DeviceId");
+
+ 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>("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("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<int?>("SubtitleStreamIndex")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("ItemId", "UserId", "CustomDataKey");
+
+ b.HasIndex("UserId");
+
+ b.HasIndex("ItemId", "UserId", "IsFavorite");
+
+ b.HasIndex("ItemId", "UserId", "LastPlayedDate");
+
+ b.HasIndex("ItemId", "UserId", "PlaybackPositionTicks");
+
+ b.HasIndex("ItemId", "UserId", "Played");
+
+ 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.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.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);
+ });
+
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Preference", b =>
+ {
+ b.HasOne("Jellyfin.Database.Implementations.Entities.User", null)
+ .WithMany("Preferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade);
+ });
+
+ 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("Images");
+
+ b.Navigation("ItemValues");
+
+ 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/20250401142247_FixAncestors.cs b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250401142247_FixAncestors.cs
new file mode 100644
index 000000000..e1220bfcf
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250401142247_FixAncestors.cs
@@ -0,0 +1,20 @@
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ /// <inheritdoc />
+ public partial class FixAncestors : Migration
+ {
+ /// <inheritdoc />
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ }
+
+ /// <inheritdoc />
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ }
+ }
+}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250405075612_FixItemValuesIndices.Designer.cs b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250405075612_FixItemValuesIndices.Designer.cs
new file mode 100644
index 000000000..4ba3352ed
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250405075612_FixItemValuesIndices.Designer.cs
@@ -0,0 +1,1694 @@
+// <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.Server.Implementations.Migrations
+{
+ [DbContext(typeof(JellyfinDbContext))]
+ [Migration("20250405075612_FixItemValuesIndices")]
+ partial class FixItemValuesIndices
+ {
+ /// <inheritdoc />
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder.HasAnnotation("ProductVersion", "9.0.3");
+
+ 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");
+
+ 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?>("DateCreatedFilesystem")
+ .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<string>("ExtraIds")
+ .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>("OriginalTitle")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Overview")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("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<string>("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("ParentId");
+
+ b.HasIndex("Path");
+
+ b.HasIndex("PresentationUniqueKey");
+
+ b.HasIndex("TopParentId", "Id");
+
+ b.HasIndex("Type", "TopParentId", "Id");
+
+ b.HasIndex("Type", "TopParentId", "PresentationUniqueKey");
+
+ b.HasIndex("Type", "TopParentId", "StartDate");
+
+ b.HasIndex("Id", "Type", "IsFolder", "IsVirtualItem");
+
+ b.HasIndex("MediaType", "TopParentId", "IsVirtualItem", "PresentationUniqueKey");
+
+ b.HasIndex("Type", "SeriesPresentationUniqueKey", "IsFolder", "IsVirtualItem");
+
+ 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);
+ });
+
+ 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");
+
+ 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", "ProviderValue", "ItemId");
+
+ 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.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<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("StreamIndex");
+
+ b.HasIndex("StreamType");
+
+ b.HasIndex("StreamIndex", "StreamType");
+
+ b.HasIndex("StreamIndex", "StreamType", "Language");
+
+ 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<int?>("ListOrder")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Role")
+ .HasColumnType("TEXT");
+
+ b.Property<int?>("SortOrder")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("ItemId", "PeopleId");
+
+ b.HasIndex("PeopleId");
+
+ b.HasIndex("ItemId", "ListOrder");
+
+ b.HasIndex("ItemId", "SortOrder");
+
+ 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<Guid?>("Permission_Permissions_Guid")
+ .HasColumnType("TEXT");
+
+ 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()
+ .HasFilter("[UserId] IS NOT NULL");
+
+ 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<Guid?>("Preference_Preferences_Guid")
+ .HasColumnType("TEXT");
+
+ 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()
+ .HasFilter("[UserId] IS NOT NULL");
+
+ 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("DeviceId");
+
+ 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>("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("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<int?>("SubtitleStreamIndex")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("ItemId", "UserId", "CustomDataKey");
+
+ b.HasIndex("UserId");
+
+ b.HasIndex("ItemId", "UserId", "IsFavorite");
+
+ b.HasIndex("ItemId", "UserId", "LastPlayedDate");
+
+ b.HasIndex("ItemId", "UserId", "PlaybackPositionTicks");
+
+ b.HasIndex("ItemId", "UserId", "Played");
+
+ 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.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.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);
+ });
+
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Preference", b =>
+ {
+ b.HasOne("Jellyfin.Database.Implementations.Entities.User", null)
+ .WithMany("Preferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade);
+ });
+
+ 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("Images");
+
+ b.Navigation("ItemValues");
+
+ 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/20250405075612_FixItemValuesIndices.cs b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250405075612_FixItemValuesIndices.cs
new file mode 100644
index 000000000..aa667bafd
--- /dev/null
+++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20250405075612_FixItemValuesIndices.cs
@@ -0,0 +1,47 @@
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ /// <inheritdoc />
+ public partial class FixItemValuesIndices : Migration
+ {
+ /// <inheritdoc />
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropIndex(
+ name: "IX_ItemValues_Type_CleanValue",
+ table: "ItemValues");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_ItemValues_Type_CleanValue",
+ table: "ItemValues",
+ columns: new[] { "Type", "CleanValue" });
+
+ migrationBuilder.CreateIndex(
+ name: "IX_ItemValues_Type_Value",
+ table: "ItemValues",
+ columns: new[] { "Type", "Value" },
+ unique: true);
+ }
+
+ /// <inheritdoc />
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropIndex(
+ name: "IX_ItemValues_Type_CleanValue",
+ table: "ItemValues");
+
+ migrationBuilder.DropIndex(
+ name: "IX_ItemValues_Type_Value",
+ table: "ItemValues");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_ItemValues_Type_CleanValue",
+ table: "ItemValues",
+ columns: new[] { "Type", "CleanValue" },
+ unique: true);
+ }
+ }
+}
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 5d8ddde08..dcdc5dd3e 100644
--- a/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/JellyfinDbModelSnapshot.cs
+++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/JellyfinDbModelSnapshot.cs
@@ -15,9 +15,9 @@ namespace Jellyfin.Server.Implementations.Migrations
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
- modelBuilder.HasAnnotation("ProductVersion", "9.0.2");
+ modelBuilder.HasAnnotation("ProductVersion", "9.0.3");
- modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.AccessSchedule", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
@@ -40,9 +40,11 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasIndex("UserId");
b.ToTable("AccessSchedules");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.ActivityLog", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.ActivityLog", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
@@ -88,9 +90,11 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasIndex("DateCreated");
b.ToTable("ActivityLogs");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.AncestorId", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.AncestorId", b =>
{
b.Property<Guid>("ItemId")
.HasColumnType("TEXT");
@@ -103,9 +107,11 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasIndex("ParentItemId");
b.ToTable("AncestorIds");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.AttachmentStreamInfo", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.AttachmentStreamInfo", b =>
{
b.Property<Guid>("ItemId")
.HasColumnType("TEXT");
@@ -114,7 +120,6 @@ namespace Jellyfin.Server.Implementations.Migrations
.HasColumnType("INTEGER");
b.Property<string>("Codec")
- .IsRequired()
.HasColumnType("TEXT");
b.Property<string>("CodecTag")
@@ -132,9 +137,11 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasKey("ItemId", "Index");
b.ToTable("AttachmentStreamInfos");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.BaseItemEntity", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
@@ -218,6 +225,9 @@ namespace Jellyfin.Server.Implementations.Migrations
b.Property<int?>("IndexNumber")
.HasColumnType("INTEGER");
+ b.Property<int?>("InheritedParentalRatingSubValue")
+ .HasColumnType("INTEGER");
+
b.Property<int?>("InheritedParentalRatingValue")
.HasColumnType("INTEGER");
@@ -380,9 +390,11 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasIndex("Type", "TopParentId", "IsVirtualItem", "PresentationUniqueKey", "DateCreated");
b.ToTable("BaseItems");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.BaseItemImageInfo", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemImageInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
@@ -415,9 +427,11 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasIndex("ItemId");
b.ToTable("BaseItemImageInfos");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.BaseItemMetadataField", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemMetadataField", b =>
{
b.Property<int>("Id")
.HasColumnType("INTEGER");
@@ -430,9 +444,11 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasIndex("ItemId");
b.ToTable("BaseItemMetadataFields");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.BaseItemProvider", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemProvider", b =>
{
b.Property<Guid>("ItemId")
.HasColumnType("TEXT");
@@ -449,9 +465,11 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasIndex("ProviderId", "ProviderValue", "ItemId");
b.ToTable("BaseItemProviders");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.BaseItemTrailerType", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemTrailerType", b =>
{
b.Property<int>("Id")
.HasColumnType("INTEGER");
@@ -464,9 +482,11 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasIndex("ItemId");
b.ToTable("BaseItemTrailerTypes");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.Chapter", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Chapter", b =>
{
b.Property<Guid>("ItemId")
.HasColumnType("TEXT");
@@ -489,9 +509,11 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasKey("ItemId", "ChapterIndex");
b.ToTable("Chapters");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.CustomItemDisplayPreferences", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.CustomItemDisplayPreferences", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
@@ -521,9 +543,11 @@ namespace Jellyfin.Server.Implementations.Migrations
.IsUnique();
b.ToTable("CustomItemDisplayPreferences");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.DisplayPreferences", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
@@ -578,9 +602,11 @@ namespace Jellyfin.Server.Implementations.Migrations
.IsUnique();
b.ToTable("DisplayPreferences");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.HomeSection", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.HomeSection", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
@@ -600,9 +626,11 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasIndex("DisplayPreferencesId");
b.ToTable("HomeSection");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.ImageInfo", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
@@ -625,9 +653,11 @@ namespace Jellyfin.Server.Implementations.Migrations
.IsUnique();
b.ToTable("ImageInfos");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.ItemDisplayPreferences", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
@@ -669,9 +699,11 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasIndex("UserId");
b.ToTable("ItemDisplayPreferences");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.ItemValue", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.ItemValue", b =>
{
b.Property<Guid>("ItemValueId")
.ValueGeneratedOnAdd()
@@ -690,13 +722,17 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasKey("ItemValueId");
- b.HasIndex("Type", "CleanValue")
+ b.HasIndex("Type", "CleanValue");
+
+ b.HasIndex("Type", "Value")
.IsUnique();
b.ToTable("ItemValues");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.ItemValueMap", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.ItemValueMap", b =>
{
b.Property<Guid>("ItemValueId")
.HasColumnType("TEXT");
@@ -709,9 +745,29 @@ namespace Jellyfin.Server.Implementations.Migrations
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.Data.Entities.MediaSegment", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.MediaSegment", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
@@ -736,9 +792,11 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasKey("Id");
b.ToTable("MediaSegments");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.MediaStreamInfo", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.MediaStreamInfo", b =>
{
b.Property<Guid>("ItemId")
.HasColumnType("TEXT");
@@ -806,6 +864,9 @@ namespace Jellyfin.Server.Implementations.Migrations
b.Property<int?>("ElPresentFlag")
.HasColumnType("INTEGER");
+ b.Property<bool?>("Hdr10PlusPresentFlag")
+ .HasColumnType("INTEGER");
+
b.Property<int?>("Height")
.HasColumnType("INTEGER");
@@ -889,9 +950,11 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasIndex("StreamIndex", "StreamType", "Language");
b.ToTable("MediaStreamInfos");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.People", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.People", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
@@ -909,9 +972,11 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasIndex("Name");
b.ToTable("Peoples");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.PeopleBaseItemMap", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.PeopleBaseItemMap", b =>
{
b.Property<Guid>("ItemId")
.HasColumnType("TEXT");
@@ -937,9 +1002,11 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasIndex("ItemId", "SortOrder");
b.ToTable("PeopleBaseItemMap");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Permission", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
@@ -968,9 +1035,11 @@ namespace Jellyfin.Server.Implementations.Migrations
.HasFilter("[UserId] IS NOT NULL");
b.ToTable("Permissions");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Preference", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
@@ -1001,9 +1070,11 @@ namespace Jellyfin.Server.Implementations.Migrations
.HasFilter("[UserId] IS NOT NULL");
b.ToTable("Preferences");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.Security.ApiKey", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Security.ApiKey", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
@@ -1030,9 +1101,11 @@ namespace Jellyfin.Server.Implementations.Migrations
.IsUnique();
b.ToTable("ApiKeys");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.Security.Device", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Security.Device", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
@@ -1088,9 +1161,11 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasIndex("UserId", "DeviceId");
b.ToTable("Devices");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.Security.DeviceOptions", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Security.DeviceOptions", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
@@ -1109,9 +1184,11 @@ namespace Jellyfin.Server.Implementations.Migrations
.IsUnique();
b.ToTable("DeviceOptions");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.TrickplayInfo", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.TrickplayInfo", b =>
{
b.Property<Guid>("ItemId")
.HasColumnType("TEXT");
@@ -1140,9 +1217,11 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasKey("ItemId", "Width");
b.ToTable("TrickplayInfos");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.User", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
@@ -1200,7 +1279,10 @@ namespace Jellyfin.Server.Implementations.Migrations
b.Property<int>("MaxActiveSessions")
.HasColumnType("INTEGER");
- b.Property<int?>("MaxParentalAgeRating")
+ b.Property<int?>("MaxParentalRatingScore")
+ .HasColumnType("INTEGER");
+
+ b.Property<int?>("MaxParentalRatingSubScore")
.HasColumnType("INTEGER");
b.Property<bool>("MustUpdatePassword")
@@ -1252,9 +1334,11 @@ namespace Jellyfin.Server.Implementations.Migrations
.IsUnique();
b.ToTable("Users");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.UserData", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.UserData", b =>
{
b.Property<Guid>("ItemId")
.HasColumnType("TEXT");
@@ -1305,27 +1389,29 @@ namespace Jellyfin.Server.Implementations.Migrations
b.HasIndex("ItemId", "UserId", "Played");
b.ToTable("UserData");
+
+ b.HasAnnotation("Sqlite:UseSqlReturningClause", false);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.AccessSchedule", b =>
{
- b.HasOne("Jellyfin.Data.Entities.User", null)
+ b.HasOne("Jellyfin.Database.Implementations.Entities.User", null)
.WithMany("AccessSchedules")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
- modelBuilder.Entity("Jellyfin.Data.Entities.AncestorId", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.AncestorId", b =>
{
- b.HasOne("Jellyfin.Data.Entities.BaseItemEntity", "Item")
- .WithMany("Children")
+ b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item")
+ .WithMany("Parents")
.HasForeignKey("ItemId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
- b.HasOne("Jellyfin.Data.Entities.BaseItemEntity", "ParentItem")
- .WithMany("ParentAncestors")
+ b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "ParentItem")
+ .WithMany("Children")
.HasForeignKey("ParentItemId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
@@ -1335,9 +1421,9 @@ namespace Jellyfin.Server.Implementations.Migrations
b.Navigation("ParentItem");
});
- modelBuilder.Entity("Jellyfin.Data.Entities.AttachmentStreamInfo", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.AttachmentStreamInfo", b =>
{
- b.HasOne("Jellyfin.Data.Entities.BaseItemEntity", "Item")
+ b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item")
.WithMany()
.HasForeignKey("ItemId")
.OnDelete(DeleteBehavior.Cascade)
@@ -1346,9 +1432,9 @@ namespace Jellyfin.Server.Implementations.Migrations
b.Navigation("Item");
});
- modelBuilder.Entity("Jellyfin.Data.Entities.BaseItemImageInfo", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemImageInfo", b =>
{
- b.HasOne("Jellyfin.Data.Entities.BaseItemEntity", "Item")
+ b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item")
.WithMany("Images")
.HasForeignKey("ItemId")
.OnDelete(DeleteBehavior.Cascade)
@@ -1357,9 +1443,9 @@ namespace Jellyfin.Server.Implementations.Migrations
b.Navigation("Item");
});
- modelBuilder.Entity("Jellyfin.Data.Entities.BaseItemMetadataField", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemMetadataField", b =>
{
- b.HasOne("Jellyfin.Data.Entities.BaseItemEntity", "Item")
+ b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item")
.WithMany("LockedFields")
.HasForeignKey("ItemId")
.OnDelete(DeleteBehavior.Cascade)
@@ -1368,9 +1454,9 @@ namespace Jellyfin.Server.Implementations.Migrations
b.Navigation("Item");
});
- modelBuilder.Entity("Jellyfin.Data.Entities.BaseItemProvider", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemProvider", b =>
{
- b.HasOne("Jellyfin.Data.Entities.BaseItemEntity", "Item")
+ b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item")
.WithMany("Provider")
.HasForeignKey("ItemId")
.OnDelete(DeleteBehavior.Cascade)
@@ -1379,9 +1465,9 @@ namespace Jellyfin.Server.Implementations.Migrations
b.Navigation("Item");
});
- modelBuilder.Entity("Jellyfin.Data.Entities.BaseItemTrailerType", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemTrailerType", b =>
{
- b.HasOne("Jellyfin.Data.Entities.BaseItemEntity", "Item")
+ b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item")
.WithMany("TrailerTypes")
.HasForeignKey("ItemId")
.OnDelete(DeleteBehavior.Cascade)
@@ -1390,9 +1476,9 @@ namespace Jellyfin.Server.Implementations.Migrations
b.Navigation("Item");
});
- modelBuilder.Entity("Jellyfin.Data.Entities.Chapter", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Chapter", b =>
{
- b.HasOne("Jellyfin.Data.Entities.BaseItemEntity", "Item")
+ b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item")
.WithMany("Chapters")
.HasForeignKey("ItemId")
.OnDelete(DeleteBehavior.Cascade)
@@ -1401,50 +1487,50 @@ namespace Jellyfin.Server.Implementations.Migrations
b.Navigation("Item");
});
- modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.DisplayPreferences", b =>
{
- b.HasOne("Jellyfin.Data.Entities.User", null)
+ b.HasOne("Jellyfin.Database.Implementations.Entities.User", null)
.WithMany("DisplayPreferences")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
- modelBuilder.Entity("Jellyfin.Data.Entities.HomeSection", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.HomeSection", b =>
{
- b.HasOne("Jellyfin.Data.Entities.DisplayPreferences", null)
+ b.HasOne("Jellyfin.Database.Implementations.Entities.DisplayPreferences", null)
.WithMany("HomeSections")
.HasForeignKey("DisplayPreferencesId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
- modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.ImageInfo", b =>
{
- b.HasOne("Jellyfin.Data.Entities.User", null)
+ b.HasOne("Jellyfin.Database.Implementations.Entities.User", null)
.WithOne("ProfileImage")
- .HasForeignKey("Jellyfin.Data.Entities.ImageInfo", "UserId")
+ .HasForeignKey("Jellyfin.Database.Implementations.Entities.ImageInfo", "UserId")
.OnDelete(DeleteBehavior.Cascade);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.ItemDisplayPreferences", b =>
{
- b.HasOne("Jellyfin.Data.Entities.User", null)
+ b.HasOne("Jellyfin.Database.Implementations.Entities.User", null)
.WithMany("ItemDisplayPreferences")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
- modelBuilder.Entity("Jellyfin.Data.Entities.ItemValueMap", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.ItemValueMap", b =>
{
- b.HasOne("Jellyfin.Data.Entities.BaseItemEntity", "Item")
+ b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item")
.WithMany("ItemValues")
.HasForeignKey("ItemId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
- b.HasOne("Jellyfin.Data.Entities.ItemValue", "ItemValue")
+ b.HasOne("Jellyfin.Database.Implementations.Entities.ItemValue", "ItemValue")
.WithMany("BaseItemsMap")
.HasForeignKey("ItemValueId")
.OnDelete(DeleteBehavior.Cascade)
@@ -1455,9 +1541,20 @@ namespace Jellyfin.Server.Implementations.Migrations
b.Navigation("ItemValue");
});
- modelBuilder.Entity("Jellyfin.Data.Entities.MediaStreamInfo", b =>
+ 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.MediaStreamInfo", b =>
{
- b.HasOne("Jellyfin.Data.Entities.BaseItemEntity", "Item")
+ b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item")
.WithMany("MediaStreams")
.HasForeignKey("ItemId")
.OnDelete(DeleteBehavior.Cascade)
@@ -1466,15 +1563,15 @@ namespace Jellyfin.Server.Implementations.Migrations
b.Navigation("Item");
});
- modelBuilder.Entity("Jellyfin.Data.Entities.PeopleBaseItemMap", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.PeopleBaseItemMap", b =>
{
- b.HasOne("Jellyfin.Data.Entities.BaseItemEntity", "Item")
+ b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item")
.WithMany("Peoples")
.HasForeignKey("ItemId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
- b.HasOne("Jellyfin.Data.Entities.People", "People")
+ b.HasOne("Jellyfin.Database.Implementations.Entities.People", "People")
.WithMany("BaseItems")
.HasForeignKey("PeopleId")
.OnDelete(DeleteBehavior.Cascade)
@@ -1485,25 +1582,25 @@ namespace Jellyfin.Server.Implementations.Migrations
b.Navigation("People");
});
- modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Permission", b =>
{
- b.HasOne("Jellyfin.Data.Entities.User", null)
+ b.HasOne("Jellyfin.Database.Implementations.Entities.User", null)
.WithMany("Permissions")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Preference", b =>
{
- b.HasOne("Jellyfin.Data.Entities.User", null)
+ b.HasOne("Jellyfin.Database.Implementations.Entities.User", null)
.WithMany("Preferences")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
- modelBuilder.Entity("Jellyfin.Data.Entities.Security.Device", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Security.Device", b =>
{
- b.HasOne("Jellyfin.Data.Entities.User", "User")
+ b.HasOne("Jellyfin.Database.Implementations.Entities.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
@@ -1512,15 +1609,15 @@ namespace Jellyfin.Server.Implementations.Migrations
b.Navigation("User");
});
- modelBuilder.Entity("Jellyfin.Data.Entities.UserData", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.UserData", b =>
{
- b.HasOne("Jellyfin.Data.Entities.BaseItemEntity", "Item")
+ b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item")
.WithMany("UserData")
.HasForeignKey("ItemId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
- b.HasOne("Jellyfin.Data.Entities.User", "User")
+ b.HasOne("Jellyfin.Database.Implementations.Entities.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
@@ -1531,7 +1628,7 @@ namespace Jellyfin.Server.Implementations.Migrations
b.Navigation("User");
});
- modelBuilder.Entity("Jellyfin.Data.Entities.BaseItemEntity", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemEntity", b =>
{
b.Navigation("Chapters");
@@ -1545,7 +1642,7 @@ namespace Jellyfin.Server.Implementations.Migrations
b.Navigation("MediaStreams");
- b.Navigation("ParentAncestors");
+ b.Navigation("Parents");
b.Navigation("Peoples");
@@ -1556,22 +1653,22 @@ namespace Jellyfin.Server.Implementations.Migrations
b.Navigation("UserData");
});
- modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.DisplayPreferences", b =>
{
b.Navigation("HomeSections");
});
- modelBuilder.Entity("Jellyfin.Data.Entities.ItemValue", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.ItemValue", b =>
{
b.Navigation("BaseItemsMap");
});
- modelBuilder.Entity("Jellyfin.Data.Entities.People", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.People", b =>
{
b.Navigation("BaseItems");
});
- modelBuilder.Entity("Jellyfin.Data.Entities.User", b =>
+ modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.User", b =>
{
b.Navigation("AccessSchedules");
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/SqliteDesignTimeJellyfinDbFactory.cs b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/SqliteDesignTimeJellyfinDbFactory.cs
index 78815c311..4d420bf8c 100644
--- a/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/SqliteDesignTimeJellyfinDbFactory.cs
+++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/SqliteDesignTimeJellyfinDbFactory.cs
@@ -1,4 +1,5 @@
using Jellyfin.Database.Implementations;
+using Jellyfin.Database.Implementations.Locking;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Logging.Abstractions;
@@ -19,7 +20,8 @@ namespace Jellyfin.Database.Providers.Sqlite.Migrations
return new JellyfinDbContext(
optionsBuilder.Options,
NullLogger<JellyfinDbContext>.Instance,
- new SqliteDatabaseProvider(null!, NullLogger<SqliteDatabaseProvider>.Instance));
+ new SqliteDatabaseProvider(null!, NullLogger<SqliteDatabaseProvider>.Instance),
+ new NoLockBehavior(NullLogger<NoLockBehavior>.Instance));
}
}
}
diff --git a/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/SqliteDatabaseProvider.cs b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/SqliteDatabaseProvider.cs
index e818c3524..dda1ca075 100644
--- a/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/SqliteDatabaseProvider.cs
+++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/SqliteDatabaseProvider.cs
@@ -1,4 +1,5 @@
using System;
+using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading;
@@ -7,6 +8,7 @@ using Jellyfin.Database.Implementations;
using MediaBrowser.Common.Configuration;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Database.Providers.Sqlite;
@@ -38,9 +40,13 @@ public sealed class SqliteDatabaseProvider : IJellyfinDatabaseProvider
/// <inheritdoc/>
public void Initialise(DbContextOptionsBuilder options)
{
- options.UseSqlite(
- $"Filename={Path.Combine(_applicationPaths.DataPath, "jellyfin.db")};Pooling=false",
- sqLiteOptions => sqLiteOptions.MigrationsAssembly(GetType().Assembly));
+ options
+ .UseSqlite(
+ $"Filename={Path.Combine(_applicationPaths.DataPath, "jellyfin.db")};Pooling=false",
+ sqLiteOptions => sqLiteOptions.MigrationsAssembly(GetType().Assembly))
+ // TODO: Remove when https://github.com/dotnet/efcore/pull/35873 is merged & released
+ .ConfigureWarnings(warnings =>
+ warnings.Ignore(RelationalEventId.NonTransactionalMigrationOperationWarning));
}
/// <inheritdoc/>
@@ -71,8 +77,13 @@ public sealed class SqliteDatabaseProvider : IJellyfinDatabaseProvider
/// <inheritdoc/>
public async Task RunShutdownTask(CancellationToken cancellationToken)
{
+ if (DbContextFactory is null)
+ {
+ return;
+ }
+
// Run before disposing the application
- var context = await DbContextFactory!.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
+ var context = await DbContextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
await using (context.ConfigureAwait(false))
{
await context.Database.ExecuteSqlRawAsync("PRAGMA optimize", cancellationToken).ConfigureAwait(false);
@@ -93,12 +104,9 @@ public sealed class SqliteDatabaseProvider : IJellyfinDatabaseProvider
var key = DateTime.UtcNow.ToString("yyyyMMddhhmmss", CultureInfo.InvariantCulture);
var path = Path.Combine(_applicationPaths.DataPath, "jellyfin.db");
var backupFile = Path.Combine(_applicationPaths.DataPath, BackupFolderName);
- if (!Directory.Exists(backupFile))
- {
- Directory.CreateDirectory(backupFile);
- }
+ Directory.CreateDirectory(backupFile);
- backupFile = Path.Combine(_applicationPaths.DataPath, $"{key}_jellyfin.db");
+ backupFile = Path.Combine(backupFile, $"{key}_jellyfin.db");
File.Copy(path, backupFile);
return Task.FromResult(key);
}
@@ -106,16 +114,54 @@ public sealed class SqliteDatabaseProvider : IJellyfinDatabaseProvider
/// <inheritdoc />
public Task RestoreBackupFast(string key, CancellationToken cancellationToken)
{
+ // ensure there are absolutly no dangling Sqlite connections.
+ SqliteConnection.ClearAllPools();
var path = Path.Combine(_applicationPaths.DataPath, "jellyfin.db");
var backupFile = Path.Combine(_applicationPaths.DataPath, BackupFolderName, $"{key}_jellyfin.db");
if (!File.Exists(backupFile))
{
- _logger.LogCritical("Tried to restore a backup that does not exist.");
+ _logger.LogCritical("Tried to restore a backup that does not exist: {Key}", key);
return Task.CompletedTask;
}
File.Copy(backupFile, path, true);
return Task.CompletedTask;
}
+
+ /// <inheritdoc />
+ public Task DeleteBackup(string key)
+ {
+ var backupFile = Path.Combine(_applicationPaths.DataPath, BackupFolderName, $"{key}_jellyfin.db");
+
+ if (!File.Exists(backupFile))
+ {
+ _logger.LogCritical("Tried to delete a backup that does not exist: {Key}", key);
+ return Task.CompletedTask;
+ }
+
+ File.Delete(backupFile);
+ return Task.CompletedTask;
+ }
+
+ /// <inheritdoc/>
+ public async Task PurgeDatabase(JellyfinDbContext dbContext, IEnumerable<string>? tableNames)
+ {
+ ArgumentNullException.ThrowIfNull(tableNames);
+
+ var deleteQueries = new List<string>();
+ foreach (var tableName in tableNames)
+ {
+ deleteQueries.Add($"DELETE FROM \"{tableName}\";");
+ }
+
+ var deleteAllQuery =
+ $"""
+ PRAGMA foreign_keys = OFF;
+ {string.Join('\n', deleteQueries)}
+ PRAGMA foreign_keys = ON;
+ """;
+
+ await dbContext.Database.ExecuteSqlRawAsync(deleteAllQuery).ConfigureAwait(false);
+ }
}
diff --git a/src/Jellyfin.Drawing.Skia/SkiaEncoder.cs b/src/Jellyfin.Drawing.Skia/SkiaEncoder.cs
index 99f7fa7f9..4626bc914 100644
--- a/src/Jellyfin.Drawing.Skia/SkiaEncoder.cs
+++ b/src/Jellyfin.Drawing.Skia/SkiaEncoder.cs
@@ -27,6 +27,16 @@ public class SkiaEncoder : IImageEncoder
private static readonly SKImageFilter _imageFilter;
private static readonly SKTypeface[] _typefaces;
+ /// <summary>
+ /// The default sampling options, equivalent to old high quality filter settings when upscaling.
+ /// </summary>
+ public static readonly SKSamplingOptions UpscaleSamplingOptions;
+
+ /// <summary>
+ /// The sampling options, used for downscaling images, equivalent to old high quality filter settings when not upscaling.
+ /// </summary>
+ public static readonly SKSamplingOptions DefaultSamplingOptions;
+
#pragma warning disable CA1810
static SkiaEncoder()
#pragma warning restore CA1810
@@ -63,6 +73,11 @@ public class SkiaEncoder : IImageEncoder
SKFontManager.Default.MatchCharacter(null, SKFontStyleWeight.Bold, SKFontStyleWidth.Normal, SKFontStyleSlant.Upright, null, 'ي'), // Arabic
SKTypeface.FromFamilyName("sans-serif", SKFontStyleWeight.Bold, SKFontStyleWidth.Normal, SKFontStyleSlant.Upright) // Default font
];
+
+ // use cubic for upscaling
+ UpscaleSamplingOptions = new SKSamplingOptions(SKCubicResampler.Mitchell);
+ // use bilinear for everything else
+ DefaultSamplingOptions = new SKSamplingOptions(SKFilterMode.Linear, SKMipmapMode.Linear);
}
/// <summary>
@@ -441,7 +456,7 @@ public class SkiaEncoder : IImageEncoder
break;
}
- surface.DrawBitmap(bitmap, 0, 0);
+ surface.DrawBitmap(bitmap, 0, 0, DefaultSamplingOptions);
return rotated;
}
catch (Exception e)
@@ -467,18 +482,23 @@ public class SkiaEncoder : IImageEncoder
{
using var surface = SKSurface.Create(targetInfo);
using var canvas = surface.Canvas;
- using var paint = new SKPaint
- {
- FilterQuality = SKFilterQuality.High,
- IsAntialias = isAntialias,
- IsDither = isDither
- };
+ using var paint = new SKPaint();
+ paint.IsAntialias = isAntialias;
+ paint.IsDither = isDither;
+
+ // Historically, kHigh implied cubic filtering, but only when upsampling.
+ // If specified kHigh, and were down-sampling, Skia used to switch back to kMedium (bilinear filtering plus mipmaps).
+ // With current skia API, passing Mitchell cubic when down-sampling will cause serious quality degradation.
+ var samplingOptions = source.Width > targetInfo.Width || source.Height > targetInfo.Height
+ ? DefaultSamplingOptions
+ : UpscaleSamplingOptions;
paint.ImageFilter = _imageFilter;
canvas.DrawBitmap(
source,
SKRect.Create(0, 0, source.Width, source.Height),
SKRect.Create(0, 0, targetInfo.Width, targetInfo.Height),
+ samplingOptions,
paint);
return surface.Snapshot();
@@ -557,20 +577,13 @@ public class SkiaEncoder : IImageEncoder
canvas.Clear(SKColor.Parse(options.BackgroundColor));
}
+ using var paint = new SKPaint();
// Add blur if option is present
- if (blur > 0)
- {
- // create image from resized bitmap to apply blur
- using var paint = new SKPaint();
- using var filter = SKImageFilter.CreateBlur(blur, blur);
- paint.ImageFilter = filter;
- canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
- }
- else
- {
- // draw resized bitmap onto canvas
- canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
- }
+ using var filter = blur > 0 ? SKImageFilter.CreateBlur(blur, blur) : null;
+ paint.ImageFilter = filter;
+
+ // create image from resized bitmap to apply blur
+ canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), DefaultSamplingOptions, paint);
// If foreground layer present then draw
if (hasForegroundColor)
@@ -696,7 +709,7 @@ public class SkiaEncoder : IImageEncoder
throw new InvalidOperationException("Image height does not match first image height.");
}
- canvas.DrawBitmap(img, x * imgWidth, y * imgHeight.Value);
+ canvas.DrawBitmap(img, x * imgWidth, y * imgHeight.Value, DefaultSamplingOptions);
}
}
diff --git a/src/Jellyfin.Drawing.Skia/SkiaExtensions.cs b/src/Jellyfin.Drawing.Skia/SkiaExtensions.cs
new file mode 100644
index 000000000..f7d6842ff
--- /dev/null
+++ b/src/Jellyfin.Drawing.Skia/SkiaExtensions.cs
@@ -0,0 +1,58 @@
+using SkiaSharp;
+
+namespace Jellyfin.Drawing.Skia;
+
+/// <summary>
+/// The SkiaSharp extensions.
+/// </summary>
+public static class SkiaExtensions
+{
+ /// <summary>
+ /// Draws an SKBitmap on the canvas with specified SkSamplingOptions.
+ /// </summary>
+ /// <param name="canvas">The SKCanvas to draw on.</param>
+ /// <param name="bitmap">The SKBitmap to draw.</param>
+ /// <param name="dest">The destination SKRect.</param>
+ /// <param name="options">The SKSamplingOptions to use for rendering.</param>
+ /// <param name="paint">Optional SKPaint to apply additional effects or styles.</param>
+ public static void DrawBitmap(this SKCanvas canvas, SKBitmap bitmap, SKRect dest, SKSamplingOptions options, SKPaint? paint = null)
+ {
+ using var image = SKImage.FromBitmap(bitmap);
+ canvas.DrawImage(image, dest, options, paint);
+ }
+
+ /// <summary>
+ /// Draws an SKBitmap on the canvas at the specified coordinates with the given SkSamplingOptions.
+ /// </summary>
+ /// <param name="canvas">The SKCanvas to draw on.</param>
+ /// <param name="bitmap">The SKBitmap to draw.</param>
+ /// <param name="x">The x-coordinate where the bitmap will be drawn.</param>
+ /// <param name="y">The y-coordinate where the bitmap will be drawn.</param>
+ /// <param name="options">The SKSamplingOptions to use for rendering.</param>
+ /// <param name="paint">Optional SKPaint to apply additional effects or styles.</param>
+ public static void DrawBitmap(this SKCanvas canvas, SKBitmap bitmap, float x, float y, SKSamplingOptions options, SKPaint? paint = null)
+ {
+ using var image = SKImage.FromBitmap(bitmap);
+ canvas.DrawImage(image, x, y, options, paint);
+ }
+
+ /// <summary>
+ /// Draws an SKBitmap on the canvas using a specified source rectangle, destination rectangle,
+ /// and optional paint, with the given SkSamplingOptions.
+ /// </summary>
+ /// <param name="canvas">The SKCanvas to draw on.</param>
+ /// <param name="bitmap">The SKBitmap to draw.</param>
+ /// <param name="source">
+ /// The source SKRect defining the portion of the bitmap to draw.
+ /// </param>
+ /// <param name="dest">
+ /// The destination SKRect defining the area on the canvas where the bitmap will be drawn.
+ /// </param>
+ /// <param name="options">The SKSamplingOptions to use for rendering.</param>
+ /// <param name="paint">Optional SKPaint to apply additional effects or styles.</param>
+ public static void DrawBitmap(this SKCanvas canvas, SKBitmap bitmap, SKRect source, SKRect dest, SKSamplingOptions options, SKPaint? paint = null)
+ {
+ using var image = SKImage.FromBitmap(bitmap);
+ canvas.DrawImage(image, source, dest, options, paint);
+ }
+}
diff --git a/src/Jellyfin.Drawing.Skia/SplashscreenBuilder.cs b/src/Jellyfin.Drawing.Skia/SplashscreenBuilder.cs
index 03733d4f8..554707a3f 100644
--- a/src/Jellyfin.Drawing.Skia/SplashscreenBuilder.cs
+++ b/src/Jellyfin.Drawing.Skia/SplashscreenBuilder.cs
@@ -101,10 +101,12 @@ public class SplashscreenBuilder
{
var imageWidth = Math.Abs(posterHeight * currentImage.Width / currentImage.Height);
using var resizedBitmap = new SKBitmap(imageWidth, posterHeight);
- currentImage.ScalePixels(resizedBitmap, SKFilterQuality.High);
-
+ var samplingOptions = currentImage.Width > imageWidth || currentImage.Height > posterHeight
+ ? SkiaEncoder.DefaultSamplingOptions
+ : SkiaEncoder.UpscaleSamplingOptions;
+ currentImage.ScalePixels(resizedBitmap, samplingOptions);
// draw on canvas
- canvas.DrawBitmap(resizedBitmap, currentWidthPos, currentHeight);
+ canvas.DrawBitmap(resizedBitmap, currentWidthPos, currentHeight, samplingOptions);
// resize to the same aspect as the original
currentWidthPos += imageWidth + Spacing;
diff --git a/src/Jellyfin.Drawing.Skia/StripCollageBuilder.cs b/src/Jellyfin.Drawing.Skia/StripCollageBuilder.cs
index b0c9c0b3c..64c33d5c2 100644
--- a/src/Jellyfin.Drawing.Skia/StripCollageBuilder.cs
+++ b/src/Jellyfin.Drawing.Skia/StripCollageBuilder.cs
@@ -109,36 +109,33 @@ public partial class StripCollageBuilder
// resize to the same aspect as the original
var backdropHeight = Math.Abs(width * backdrop.Height / backdrop.Width);
- using var residedBackdrop = SkiaEncoder.ResizeImage(backdrop, new SKImageInfo(width, backdropHeight, backdrop.ColorType, backdrop.AlphaType, backdrop.ColorSpace));
+ using var resizedBackdrop = SkiaEncoder.ResizeImage(backdrop, new SKImageInfo(width, backdropHeight, backdrop.ColorType, backdrop.AlphaType, backdrop.ColorSpace));
+ using var paint = new SKPaint();
// draw the backdrop
- canvas.DrawImage(residedBackdrop, 0, 0);
+ canvas.DrawImage(resizedBackdrop, 0, 0, SkiaEncoder.DefaultSamplingOptions, paint);
// draw shadow rectangle
- using var paintColor = new SKPaint
- {
- Color = SKColors.Black.WithAlpha(0x78),
- Style = SKPaintStyle.Fill
- };
+ using var paintColor = new SKPaint();
+ paintColor.Color = SKColors.Black.WithAlpha(0x78);
+ paintColor.Style = SKPaintStyle.Fill;
canvas.DrawRect(0, 0, width, height, paintColor);
var typeFace = SkiaEncoder.DefaultTypeFace;
// draw library name
- using var textPaint = new SKPaint
- {
- Color = SKColors.White,
- Style = SKPaintStyle.Fill,
- TextSize = 112,
- TextAlign = SKTextAlign.Left,
- Typeface = typeFace,
- IsAntialias = true
- };
+ using var textFont = new SKFont();
+ textFont.Size = 112;
+ textFont.Typeface = typeFace;
+ using var textPaint = new SKPaint();
+ textPaint.Color = SKColors.White;
+ textPaint.Style = SKPaintStyle.Fill;
+ textPaint.IsAntialias = true;
// scale down text to 90% of the width if text is larger than 95% of the width
- var textWidth = textPaint.MeasureText(libraryName);
+ var textWidth = textFont.MeasureText(libraryName);
if (textWidth > width * 0.95)
{
- textPaint.TextSize = 0.9f * width * textPaint.TextSize / textWidth;
+ textFont.Size = 0.9f * width * textFont.Size / textWidth;
}
if (string.IsNullOrWhiteSpace(libraryName))
@@ -146,23 +143,22 @@ public partial class StripCollageBuilder
return bitmap;
}
- var realWidth = DrawText(null, 0, (height / 2f) + (textPaint.FontMetrics.XHeight / 2), libraryName, textPaint);
+ var realWidth = DrawText(null, 0, (height / 2f) + (textFont.Metrics.XHeight / 2), libraryName, textPaint, textFont);
if (realWidth > width * 0.95)
{
- textPaint.TextSize = 0.9f * width * textPaint.TextSize / realWidth;
- realWidth = DrawText(null, 0, (height / 2f) + (textPaint.FontMetrics.XHeight / 2), libraryName, textPaint);
+ textFont.Size = 0.9f * width * textFont.Size / realWidth;
+ realWidth = DrawText(null, 0, (height / 2f) + (textFont.Metrics.XHeight / 2), libraryName, textPaint, textFont);
}
var padding = (width - realWidth) / 2;
if (IsRtlTextRegex().IsMatch(libraryName))
{
- textPaint.TextAlign = SKTextAlign.Right;
- DrawText(canvas, width - padding, (height / 2f) + (textPaint.FontMetrics.XHeight / 2), libraryName, textPaint, true);
+ DrawText(canvas, width - padding, (height / 2f) + (textFont.Metrics.XHeight / 2), libraryName, textPaint, textFont, true);
}
else
{
- DrawText(canvas, padding, (height / 2f) + (textPaint.FontMetrics.XHeight / 2), libraryName, textPaint);
+ DrawText(canvas, padding, (height / 2f) + (textFont.Metrics.XHeight / 2), libraryName, textPaint, textFont);
}
return bitmap;
@@ -188,14 +184,15 @@ public partial class StripCollageBuilder
continue;
}
- // Scale image. The FromBitmap creates a copy
+ // Scale image
var imageInfo = new SKImageInfo(cellWidth, cellHeight, currentBitmap.ColorType, currentBitmap.AlphaType, currentBitmap.ColorSpace);
using var resizeImage = SkiaEncoder.ResizeImage(currentBitmap, imageInfo);
+ using var paint = new SKPaint();
// draw this image into the strip at the next position
var xPos = x * cellWidth;
var yPos = y * cellHeight;
- canvas.DrawImage(resizeImage, xPos, yPos);
+ canvas.DrawImage(resizeImage, xPos, yPos, SkiaEncoder.DefaultSamplingOptions, paint);
}
}
@@ -210,11 +207,13 @@ public partial class StripCollageBuilder
/// <param name="y">y position of the canvas to draw text.</param>
/// <param name="text">The text to draw.</param>
/// <param name="textPaint">The SKPaint to style the text.</param>
+ /// <param name="textFont">The SKFont to style the text.</param>
+ /// <param name="alignment">The alignment of the text. Default aligns to left.</param>
/// <returns>The width of the text.</returns>
- private static float MeasureAndDrawText(SKCanvas? canvas, float x, float y, string text, SKPaint textPaint)
+ private static float MeasureAndDrawText(SKCanvas? canvas, float x, float y, string text, SKPaint textPaint, SKFont textFont, SKTextAlign alignment = SKTextAlign.Left)
{
- var width = textPaint.MeasureText(text);
- canvas?.DrawShapedText(text, x, y, textPaint);
+ var width = textFont.MeasureText(text);
+ canvas?.DrawShapedText(text, x, y, alignment, textFont, textPaint);
return width;
}
@@ -226,16 +225,18 @@ public partial class StripCollageBuilder
/// <param name="y">y position of the canvas to draw text.</param>
/// <param name="text">The text to draw.</param>
/// <param name="textPaint">The SKPaint to style the text.</param>
+ /// <param name="textFont">The SKFont to style the text.</param>
/// <param name="isRtl">If true, render from right to left.</param>
/// <returns>The width of the text.</returns>
- private static float DrawText(SKCanvas? canvas, float x, float y, string text, SKPaint textPaint, bool isRtl = false)
+ private static float DrawText(SKCanvas? canvas, float x, float y, string text, SKPaint textPaint, SKFont textFont, bool isRtl = false)
{
float width = 0;
+ var alignment = isRtl ? SKTextAlign.Right : SKTextAlign.Left;
- if (textPaint.ContainsGlyphs(text))
+ if (textFont.ContainsGlyphs(text))
{
// Current font can render all characters in text
- return MeasureAndDrawText(canvas, x, y, text, textPaint);
+ return MeasureAndDrawText(canvas, x, y, text, textPaint, textFont, alignment);
}
// Iterate over all text elements using TextElementEnumerator
@@ -248,7 +249,7 @@ public partial class StripCollageBuilder
{
bool notAtEnd;
var textElement = enumerator.GetTextElement();
- if (textPaint.ContainsGlyphs(textElement))
+ if (textFont.ContainsGlyphs(textElement))
{
continue;
}
@@ -258,12 +259,12 @@ public partial class StripCollageBuilder
if (start != enumerator.ElementIndex)
{
var regularText = text.Substring(start, enumerator.ElementIndex - start);
- width += MeasureAndDrawText(canvas, MoveX(x, width), y, regularText, textPaint);
+ width += MeasureAndDrawText(canvas, MoveX(x, width), y, regularText, textPaint, textFont, alignment);
start = enumerator.ElementIndex;
}
// Search for next point where current font can render the character there
- while ((notAtEnd = enumerator.MoveNext()) && !textPaint.ContainsGlyphs(enumerator.GetTextElement()))
+ while ((notAtEnd = enumerator.MoveNext()) && !textFont.ContainsGlyphs(enumerator.GetTextElement()))
{
// Do nothing, just move enumerator to the point where current font can render the character
}
@@ -278,21 +279,21 @@ public partial class StripCollageBuilder
if (fallback is not null)
{
+ using var fallbackTextFont = new SKFont();
+ fallbackTextFont.Size = textFont.Size;
+ fallbackTextFont.Typeface = fallback;
using var fallbackTextPaint = new SKPaint();
fallbackTextPaint.Color = textPaint.Color;
fallbackTextPaint.Style = textPaint.Style;
- fallbackTextPaint.TextSize = textPaint.TextSize;
- fallbackTextPaint.TextAlign = textPaint.TextAlign;
- fallbackTextPaint.Typeface = fallback;
fallbackTextPaint.IsAntialias = textPaint.IsAntialias;
// Do the search recursively to select all possible fonts
- width += DrawText(canvas, MoveX(x, width), y, subtext, fallbackTextPaint, isRtl);
+ width += DrawText(canvas, MoveX(x, width), y, subtext, fallbackTextPaint, fallbackTextFont, isRtl);
}
else
{
// Used up all fonts and no fonts can be found, just use current font
- width += MeasureAndDrawText(canvas, MoveX(x, width), y, text[start..], textPaint);
+ width += MeasureAndDrawText(canvas, MoveX(x, width), y, text[start..], textPaint, textFont, alignment);
}
start = notAtEnd ? enumerator.ElementIndex : text.Length;
@@ -301,7 +302,7 @@ public partial class StripCollageBuilder
// Render the remaining text that current fonts can render
if (start < text.Length)
{
- width += MeasureAndDrawText(canvas, MoveX(x, width), y, text[start..], textPaint);
+ width += MeasureAndDrawText(canvas, MoveX(x, width), y, text[start..], textPaint, textFont, alignment);
}
return width;
diff --git a/src/Jellyfin.Drawing.Skia/UnplayedCountIndicator.cs b/src/Jellyfin.Drawing.Skia/UnplayedCountIndicator.cs
index 456b84b8c..46c48357e 100644
--- a/src/Jellyfin.Drawing.Skia/UnplayedCountIndicator.cs
+++ b/src/Jellyfin.Drawing.Skia/UnplayedCountIndicator.cs
@@ -34,10 +34,12 @@ public static class UnplayedCountIndicator
Style = SKPaintStyle.Fill
};
+ using var font = new SKFont();
+
canvas.DrawCircle(x, OffsetFromTopRightCorner, 20, paint);
paint.Color = new SKColor(255, 255, 255, 255);
- paint.TextSize = 24;
+ font.Size = 24;
paint.IsAntialias = true;
var y = OffsetFromTopRightCorner + 9;
@@ -55,9 +57,9 @@ public static class UnplayedCountIndicator
{
x -= 15;
y -= 2;
- paint.TextSize = 18;
+ font.Size = 18;
}
- canvas.DrawText(text, x, y, paint);
+ canvas.DrawText(text, x, y, font, paint);
}
}
diff --git a/src/Jellyfin.Drawing/ImageProcessor.cs b/src/Jellyfin.Drawing/ImageProcessor.cs
index 7718f6c6a..46e5213a8 100644
--- a/src/Jellyfin.Drawing/ImageProcessor.cs
+++ b/src/Jellyfin.Drawing/ImageProcessor.cs
@@ -34,7 +34,7 @@ public sealed class ImageProcessor : IImageProcessor, IDisposable
private const char Version = '3';
private static readonly HashSet<string> _transparentImageTypes
- = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".png", ".webp", ".gif" };
+ = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".png", ".webp", ".gif", ".svg" };
private readonly ILogger<ImageProcessor> _logger;
private readonly IFileSystem _fileSystem;
@@ -524,11 +524,11 @@ public sealed class ImageProcessor : IImageProcessor, IDisposable
/// <inheritdoc />
public void CreateImageCollage(ImageCollageOptions options, string? libraryName)
{
- _logger.LogInformation("Creating image collage and saving to {Path}", options.OutputPath);
+ _logger.LogDebug("Creating image collage and saving to {Path}", options.OutputPath);
_imageEncoder.CreateImageCollage(options, libraryName);
- _logger.LogInformation("Completed creation of image collage and saved to {Path}", options.OutputPath);
+ _logger.LogDebug("Completed creation of image collage and saved to {Path}", options.OutputPath);
}
/// <inheritdoc />
diff --git a/src/Jellyfin.Extensions/FileHelper.cs b/src/Jellyfin.Extensions/FileHelper.cs
new file mode 100644
index 000000000..b1ccf8d47
--- /dev/null
+++ b/src/Jellyfin.Extensions/FileHelper.cs
@@ -0,0 +1,20 @@
+using System.IO;
+
+namespace Jellyfin.Extensions;
+
+/// <summary>
+/// Provides helper functions for <see cref="File" />.
+/// </summary>
+public static class FileHelper
+{
+ /// <summary>
+ /// Creates, or truncates a file in the specified path.
+ /// </summary>
+ /// <param name="path">The path and name of the file to create.</param>
+ public static void CreateEmpty(string path)
+ {
+ using (File.OpenHandle(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
+ {
+ }
+ }
+}
diff --git a/src/Jellyfin.Extensions/StringExtensions.cs b/src/Jellyfin.Extensions/StringExtensions.cs
index 715cbf220..60df47113 100644
--- a/src/Jellyfin.Extensions/StringExtensions.cs
+++ b/src/Jellyfin.Extensions/StringExtensions.cs
@@ -135,5 +135,18 @@ namespace Jellyfin.Extensions
{
return values.Select(i => (i ?? string.Empty).Trim());
}
+
+ /// <summary>
+ /// Truncates a string at the first null character ('\0').
+ /// </summary>
+ /// <param name="text">The input string.</param>
+ /// <returns>
+ /// The substring up to (but not including) the first null character,
+ /// or the original string if no null character is present.
+ /// </returns>
+ public static string TruncateAtNull(this string text)
+ {
+ return string.IsNullOrEmpty(text) ? text : text.AsSpan().LeftPart('\0').ToString();
+ }
}
}
diff --git a/src/Jellyfin.LiveTv/Channels/ChannelManager.cs b/src/Jellyfin.LiveTv/Channels/ChannelManager.cs
index 0ca294a28..74182171f 100644
--- a/src/Jellyfin.LiveTv/Channels/ChannelManager.cs
+++ b/src/Jellyfin.LiveTv/Channels/ChannelManager.cs
@@ -363,7 +363,7 @@ namespace Jellyfin.LiveTv.Channels
Directory.CreateDirectory(Path.GetDirectoryName(path));
- FileStream createStream = File.Create(path);
+ FileStream createStream = AsyncFile.Create(path);
await using (createStream.ConfigureAwait(false))
{
await JsonSerializer.SerializeAsync(createStream, mediaSources, _jsonOptions).ConfigureAwait(false);
@@ -445,12 +445,13 @@ namespace Jellyfin.LiveTv.Channels
if (item is null)
{
+ var info = Directory.CreateDirectory(path);
item = new Channel
{
Name = channelInfo.Name,
Id = id,
- DateCreated = _fileSystem.GetCreationTimeUtc(path),
- DateModified = _fileSystem.GetLastWriteTimeUtc(path)
+ DateCreated = info.CreationTimeUtc,
+ DateModified = info.LastWriteTimeUtc
};
isNew = true;
@@ -866,7 +867,7 @@ namespace Jellyfin.LiveTv.Channels
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
- var createStream = File.Create(path);
+ var createStream = AsyncFile.Create(path);
await using (createStream.ConfigureAwait(false))
{
await JsonSerializer.SerializeAsync(createStream, result, _jsonOptions).ConfigureAwait(false);
diff --git a/src/Jellyfin.LiveTv/LiveTvDtoService.cs b/src/Jellyfin.LiveTv/LiveTvDtoService.cs
index 55b056d3d..acf168cf1 100644
--- a/src/Jellyfin.LiveTv/LiveTvDtoService.cs
+++ b/src/Jellyfin.LiveTv/LiveTvDtoService.cs
@@ -221,7 +221,7 @@ namespace Jellyfin.LiveTv
try
{
dto.ParentPrimaryImageTag = _imageProcessor.GetImageCacheTag(program, image);
- dto.ParentPrimaryImageItemId = program.Id.ToString("N", CultureInfo.InvariantCulture);
+ dto.ParentPrimaryImageItemId = program.Id;
}
catch (Exception ex)
{
@@ -327,7 +327,7 @@ namespace Jellyfin.LiveTv
try
{
dto.ParentPrimaryImageTag = _imageProcessor.GetImageCacheTag(program, image);
- dto.ParentPrimaryImageItemId = program.Id.ToString("N", CultureInfo.InvariantCulture);
+ dto.ParentPrimaryImageItemId = program.Id;
}
catch (Exception ex)
{
diff --git a/src/Jellyfin.LiveTv/LiveTvManager.cs b/src/Jellyfin.LiveTv/LiveTvManager.cs
index 40adb51a5..53bc6751f 100644
--- a/src/Jellyfin.LiveTv/LiveTvManager.cs
+++ b/src/Jellyfin.LiveTv/LiveTvManager.cs
@@ -125,8 +125,8 @@ namespace Jellyfin.LiveTv
IsKids = query.IsKids,
IsSports = query.IsSports,
IsSeries = query.IsSeries,
- IncludeItemTypes = new[] { BaseItemKind.LiveTvChannel },
- TopParentIds = new[] { topFolder.Id },
+ IncludeItemTypes = [BaseItemKind.LiveTvChannel],
+ TopParentIds = [topFolder.Id],
IsFavorite = query.IsFavorite,
IsLiked = query.IsLiked,
StartIndex = query.StartIndex,
@@ -199,17 +199,17 @@ namespace Jellyfin.LiveTv
if (query.OrderBy.Count == 0)
{
// Unless something else was specified, order by start date to take advantage of a specialized index
- query.OrderBy = new[]
- {
+ query.OrderBy =
+ [
(ItemSortBy.StartDate, SortOrder.Ascending)
- };
+ ];
}
RemoveFields(options);
var internalQuery = new InternalItemsQuery(user)
{
- IncludeItemTypes = new[] { BaseItemKind.LiveTvProgram },
+ IncludeItemTypes = [BaseItemKind.LiveTvProgram],
MinEndDate = query.MinEndDate,
MinStartDate = query.MinStartDate,
MaxEndDate = query.MaxEndDate,
@@ -226,7 +226,7 @@ namespace Jellyfin.LiveTv
Limit = query.Limit,
OrderBy = query.OrderBy,
EnableTotalRecordCount = query.EnableTotalRecordCount,
- TopParentIds = new[] { topFolder.Id },
+ TopParentIds = [topFolder.Id],
Name = query.Name,
DtoOptions = options,
HasAired = query.HasAired,
@@ -272,7 +272,7 @@ namespace Jellyfin.LiveTv
var internalQuery = new InternalItemsQuery(user)
{
- IncludeItemTypes = new[] { BaseItemKind.LiveTvProgram },
+ IncludeItemTypes = [BaseItemKind.LiveTvProgram],
IsAiring = query.IsAiring,
HasAired = query.HasAired,
IsNews = query.IsNews,
@@ -281,8 +281,8 @@ namespace Jellyfin.LiveTv
IsSports = query.IsSports,
IsKids = query.IsKids,
EnableTotalRecordCount = query.EnableTotalRecordCount,
- OrderBy = new[] { (ItemSortBy.StartDate, SortOrder.Ascending) },
- TopParentIds = new[] { topFolder.Id },
+ OrderBy = [(ItemSortBy.StartDate, SortOrder.Ascending)],
+ TopParentIds = [topFolder.Id],
DtoOptions = options,
GenreIds = query.GenreIds
};
@@ -497,19 +497,19 @@ namespace Jellyfin.LiveTv
// TotalRecordCount = items.Length
// };
- dtoOptions.Fields = dtoOptions.Fields.Concat(new[] { ItemFields.Tags }).Distinct().ToArray();
+ dtoOptions.Fields = dtoOptions.Fields.Concat([ItemFields.Tags]).Distinct().ToArray();
}
var result = _libraryManager.GetItemsResult(new InternalItemsQuery(user)
{
- MediaTypes = new[] { MediaType.Video },
+ MediaTypes = [MediaType.Video],
Recursive = true,
AncestorIds = folderIds,
IsFolder = false,
IsVirtualItem = false,
Limit = limit,
StartIndex = query.StartIndex,
- OrderBy = new[] { (ItemSortBy.DateCreated, SortOrder.Descending) },
+ OrderBy = [(ItemSortBy.DateCreated, SortOrder.Descending)],
EnableTotalRecordCount = query.EnableTotalRecordCount,
IncludeItemTypes = includeItemTypes.ToArray(),
ExcludeItemTypes = excludeItemTypes.ToArray(),
@@ -959,13 +959,13 @@ namespace Jellyfin.LiveTv
var programs = options.AddCurrentProgram ? _libraryManager.GetItemList(new InternalItemsQuery(user)
{
- IncludeItemTypes = new[] { BaseItemKind.LiveTvProgram },
+ IncludeItemTypes = [BaseItemKind.LiveTvProgram],
ChannelIds = channelIds,
MaxStartDate = now,
MinEndDate = now,
Limit = channelIds.Length,
- OrderBy = new[] { (ItemSortBy.StartDate, SortOrder.Ascending) },
- TopParentIds = new[] { GetInternalLiveTvFolder(CancellationToken.None).Id },
+ OrderBy = [(ItemSortBy.StartDate, SortOrder.Ascending)],
+ TopParentIds = [GetInternalLiveTvFolder(CancellationToken.None).Id],
DtoOptions = options
}) : new List<BaseItem>();
@@ -1269,7 +1269,7 @@ namespace Jellyfin.LiveTv
{
var folders = _recordingsManager.GetRecordingFolders()
.SelectMany(i => i.Locations)
- .Distinct(StringComparer.OrdinalIgnoreCase)
+ .Distinct()
.Select(i => _libraryManager.FindByPath(i, true))
.Where(i => i is not null && i.IsVisibleStandalone(user))
.SelectMany(i => _libraryManager.GetCollectionFolders(i))
diff --git a/src/Jellyfin.LiveTv/Recordings/RecordingsManager.cs b/src/Jellyfin.LiveTv/Recordings/RecordingsManager.cs
index 9ca5d7420..846f9baf7 100644
--- a/src/Jellyfin.LiveTv/Recordings/RecordingsManager.cs
+++ b/src/Jellyfin.LiveTv/Recordings/RecordingsManager.cs
@@ -230,7 +230,7 @@ public sealed class RecordingsManager : IRecordingsManager, IDisposable
if (pathsAdded.Count > 0 || pathsToRemove.Count > 0)
{
pathsAdded.InsertRange(0, config.MediaLocationsCreated);
- config.MediaLocationsCreated = pathsAdded.Except(pathsToRemove).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
+ config.MediaLocationsCreated = pathsAdded.Except(pathsToRemove).Distinct().ToArray();
_config.SaveConfiguration("livetv", config);
}
diff --git a/src/Jellyfin.LiveTv/TunerHosts/M3UTunerHost.cs b/src/Jellyfin.LiveTv/TunerHosts/M3UTunerHost.cs
index be81171a0..fb606be0e 100644
--- a/src/Jellyfin.LiveTv/TunerHosts/M3UTunerHost.cs
+++ b/src/Jellyfin.LiveTv/TunerHosts/M3UTunerHost.cs
@@ -190,7 +190,7 @@ namespace Jellyfin.LiveTv.TunerHosts
RequiresClosing = true,
RequiresLooping = info.EnableStreamLooping,
- ReadAtNativeFramerate = false,
+ ReadAtNativeFramerate = info.ReadAtNativeFramerate,
Id = channel.Path.GetMD5().ToString("N", CultureInfo.InvariantCulture),
IsInfiniteStream = true,
diff --git a/src/Jellyfin.MediaEncoding.Hls/Cache/CacheDecorator.cs b/src/Jellyfin.MediaEncoding.Hls/Cache/CacheDecorator.cs
index 127f4079c..8ca0e869a 100644
--- a/src/Jellyfin.MediaEncoding.Hls/Cache/CacheDecorator.cs
+++ b/src/Jellyfin.MediaEncoding.Hls/Cache/CacheDecorator.cs
@@ -1,13 +1,12 @@
+#pragma warning disable CA1826 // Do not use Enumerable methods on indexable collections
+
using System;
using System.Diagnostics.CodeAnalysis;
-using System.Globalization;
-using System.IO;
-using System.Text.Json;
-using Jellyfin.Extensions.Json;
+using System.Linq;
+using System.Threading;
using Jellyfin.MediaEncoding.Hls.Extractors;
using Jellyfin.MediaEncoding.Keyframes;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.Persistence;
using Microsoft.Extensions.Logging;
namespace Jellyfin.MediaEncoding.Hls.Cache;
@@ -15,82 +14,48 @@ namespace Jellyfin.MediaEncoding.Hls.Cache;
/// <inheritdoc />
public class CacheDecorator : IKeyframeExtractor
{
+ private readonly IKeyframeRepository _keyframeRepository;
private readonly IKeyframeExtractor _keyframeExtractor;
private readonly ILogger<CacheDecorator> _logger;
private readonly string _keyframeExtractorName;
- private static readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
- private readonly string _keyframeCachePath;
/// <summary>
/// Initializes a new instance of the <see cref="CacheDecorator"/> class.
/// </summary>
- /// <param name="applicationPaths">An instance of the <see cref="IApplicationPaths"/> interface.</param>
+ /// <param name="keyframeRepository">An instance of the <see cref="IKeyframeRepository"/> interface.</param>
/// <param name="keyframeExtractor">An instance of the <see cref="IKeyframeExtractor"/> interface.</param>
/// <param name="logger">An instance of the <see cref="ILogger{CacheDecorator}"/> interface.</param>
- public CacheDecorator(IApplicationPaths applicationPaths, IKeyframeExtractor keyframeExtractor, ILogger<CacheDecorator> logger)
+ public CacheDecorator(IKeyframeRepository keyframeRepository, IKeyframeExtractor keyframeExtractor, ILogger<CacheDecorator> logger)
{
- ArgumentNullException.ThrowIfNull(applicationPaths);
+ ArgumentNullException.ThrowIfNull(keyframeRepository);
ArgumentNullException.ThrowIfNull(keyframeExtractor);
+ _keyframeRepository = keyframeRepository;
_keyframeExtractor = keyframeExtractor;
_logger = logger;
_keyframeExtractorName = keyframeExtractor.GetType().Name;
- // TODO make the dir configurable
- _keyframeCachePath = Path.Combine(applicationPaths.DataPath, "keyframes");
}
/// <inheritdoc />
public bool IsMetadataBased => _keyframeExtractor.IsMetadataBased;
/// <inheritdoc />
- public bool TryExtractKeyframes(string filePath, [NotNullWhen(true)] out KeyframeData? keyframeData)
+ public bool TryExtractKeyframes(Guid itemId, string filePath, [NotNullWhen(true)] out KeyframeData? keyframeData)
{
- keyframeData = null;
- var cachePath = GetCachePath(_keyframeCachePath, filePath);
- if (TryReadFromCache(cachePath, out var cachedResult))
+ keyframeData = _keyframeRepository.GetKeyframeData(itemId).FirstOrDefault();
+ if (keyframeData is null)
{
- keyframeData = cachedResult;
- return true;
+ if (!_keyframeExtractor.TryExtractKeyframes(itemId, filePath, out var result))
+ {
+ _logger.LogDebug("Failed to extract keyframes using {ExtractorName}", _keyframeExtractorName);
+ return false;
+ }
+
+ _logger.LogDebug("Successfully extracted keyframes using {ExtractorName}", _keyframeExtractorName);
+ keyframeData = result;
+ _keyframeRepository.SaveKeyframeDataAsync(itemId, keyframeData, CancellationToken.None).GetAwaiter().GetResult();
}
- if (!_keyframeExtractor.TryExtractKeyframes(filePath, out var result))
- {
- _logger.LogDebug("Failed to extract keyframes using {ExtractorName}", _keyframeExtractorName);
- return false;
- }
-
- _logger.LogDebug("Successfully extracted keyframes using {ExtractorName}", _keyframeExtractorName);
- keyframeData = result;
- SaveToCache(cachePath, keyframeData);
return true;
}
-
- private static void SaveToCache(string cachePath, KeyframeData keyframeData)
- {
- var json = JsonSerializer.Serialize(keyframeData, _jsonOptions);
- Directory.CreateDirectory(Path.GetDirectoryName(cachePath) ?? throw new ArgumentException($"Provided path ({cachePath}) is not valid.", nameof(cachePath)));
- File.WriteAllText(cachePath, json);
- }
-
- private static string GetCachePath(string keyframeCachePath, string filePath)
- {
- var lastWriteTimeUtc = File.GetLastWriteTimeUtc(filePath);
- ReadOnlySpan<char> filename = (filePath + "_" + lastWriteTimeUtc.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5() + ".json";
- var prefix = filename[..1];
-
- return Path.Join(keyframeCachePath, prefix, filename);
- }
-
- private static bool TryReadFromCache(string cachePath, [NotNullWhen(true)] out KeyframeData? cachedResult)
- {
- if (File.Exists(cachePath))
- {
- var bytes = File.ReadAllBytes(cachePath);
- cachedResult = JsonSerializer.Deserialize<KeyframeData>(bytes, _jsonOptions);
- return cachedResult is not null;
- }
-
- cachedResult = null;
- return false;
- }
}
diff --git a/src/Jellyfin.MediaEncoding.Hls/Extractors/FfProbeKeyframeExtractor.cs b/src/Jellyfin.MediaEncoding.Hls/Extractors/FfProbeKeyframeExtractor.cs
index a8daeeb78..a69746fe0 100644
--- a/src/Jellyfin.MediaEncoding.Hls/Extractors/FfProbeKeyframeExtractor.cs
+++ b/src/Jellyfin.MediaEncoding.Hls/Extractors/FfProbeKeyframeExtractor.cs
@@ -34,7 +34,7 @@ public class FfProbeKeyframeExtractor : IKeyframeExtractor
public bool IsMetadataBased => false;
/// <inheritdoc />
- public bool TryExtractKeyframes(string filePath, [NotNullWhen(true)] out KeyframeData? keyframeData)
+ public bool TryExtractKeyframes(Guid itemId, string filePath, [NotNullWhen(true)] out KeyframeData? keyframeData)
{
if (!_namingOptions.VideoFileExtensions.Contains(Path.GetExtension(filePath.AsSpan()), StringComparison.OrdinalIgnoreCase))
{
diff --git a/src/Jellyfin.MediaEncoding.Hls/Extractors/IKeyframeExtractor.cs b/src/Jellyfin.MediaEncoding.Hls/Extractors/IKeyframeExtractor.cs
index 083e93de1..84bccbc72 100644
--- a/src/Jellyfin.MediaEncoding.Hls/Extractors/IKeyframeExtractor.cs
+++ b/src/Jellyfin.MediaEncoding.Hls/Extractors/IKeyframeExtractor.cs
@@ -1,3 +1,4 @@
+using System;
using System.Diagnostics.CodeAnalysis;
using Jellyfin.MediaEncoding.Keyframes;
@@ -16,8 +17,9 @@ public interface IKeyframeExtractor
/// <summary>
/// Attempt to extract keyframes.
/// </summary>
+ /// <param name="itemId">The item id.</param>
/// <param name="filePath">The path to the file.</param>
/// <param name="keyframeData">The keyframes.</param>
/// <returns>A value indicating whether the keyframe extraction was successful.</returns>
- bool TryExtractKeyframes(string filePath, [NotNullWhen(true)] out KeyframeData? keyframeData);
+ bool TryExtractKeyframes(Guid itemId, string filePath, [NotNullWhen(true)] out KeyframeData? keyframeData);
}
diff --git a/src/Jellyfin.MediaEncoding.Hls/Extractors/MatroskaKeyframeExtractor.cs b/src/Jellyfin.MediaEncoding.Hls/Extractors/MatroskaKeyframeExtractor.cs
index 1100f8cd5..c7758e919 100644
--- a/src/Jellyfin.MediaEncoding.Hls/Extractors/MatroskaKeyframeExtractor.cs
+++ b/src/Jellyfin.MediaEncoding.Hls/Extractors/MatroskaKeyframeExtractor.cs
@@ -24,7 +24,7 @@ public class MatroskaKeyframeExtractor : IKeyframeExtractor
public bool IsMetadataBased => true;
/// <inheritdoc />
- public bool TryExtractKeyframes(string filePath, [NotNullWhen(true)] out KeyframeData? keyframeData)
+ public bool TryExtractKeyframes(Guid itemId, string filePath, [NotNullWhen(true)] out KeyframeData? keyframeData)
{
if (!filePath.AsSpan().EndsWith(".mkv", StringComparison.OrdinalIgnoreCase))
{
diff --git a/src/Jellyfin.MediaEncoding.Hls/Jellyfin.MediaEncoding.Hls.csproj b/src/Jellyfin.MediaEncoding.Hls/Jellyfin.MediaEncoding.Hls.csproj
index dc581724a..80b5aa84e 100644
--- a/src/Jellyfin.MediaEncoding.Hls/Jellyfin.MediaEncoding.Hls.csproj
+++ b/src/Jellyfin.MediaEncoding.Hls/Jellyfin.MediaEncoding.Hls.csproj
@@ -7,6 +7,7 @@
<ItemGroup>
<ProjectReference Include="../../MediaBrowser.Common/MediaBrowser.Common.csproj" />
+ <ProjectReference Include="../../MediaBrowser.Model/MediaBrowser.Model.csproj" />
<ProjectReference Include="../../MediaBrowser.Controller/MediaBrowser.Controller.csproj" />
<ProjectReference Include="../Jellyfin.MediaEncoding.Keyframes/Jellyfin.MediaEncoding.Keyframes.csproj" />
</ItemGroup>
diff --git a/src/Jellyfin.MediaEncoding.Hls/Playlist/CreateMainPlaylistRequest.cs b/src/Jellyfin.MediaEncoding.Hls/Playlist/CreateMainPlaylistRequest.cs
index 21d9bb658..f5af50062 100644
--- a/src/Jellyfin.MediaEncoding.Hls/Playlist/CreateMainPlaylistRequest.cs
+++ b/src/Jellyfin.MediaEncoding.Hls/Playlist/CreateMainPlaylistRequest.cs
@@ -1,3 +1,5 @@
+using System;
+
namespace Jellyfin.MediaEncoding.Hls.Playlist;
/// <summary>
@@ -8,6 +10,7 @@ public class CreateMainPlaylistRequest
/// <summary>
/// Initializes a new instance of the <see cref="CreateMainPlaylistRequest"/> class.
/// </summary>
+ /// <param name="mediaSourceId">The media source id.</param>
/// <param name="filePath">The absolute file path to the file.</param>
/// <param name="desiredSegmentLengthMs">The desired segment length in milliseconds.</param>
/// <param name="totalRuntimeTicks">The total duration of the file in ticks.</param>
@@ -15,8 +18,9 @@ public class CreateMainPlaylistRequest
/// <param name="endpointPrefix">The URI prefix for the relative URL in the playlist.</param>
/// <param name="queryString">The desired query string to append (must start with ?).</param>
/// <param name="isRemuxingVideo">Whether the video is being remuxed.</param>
- public CreateMainPlaylistRequest(string filePath, int desiredSegmentLengthMs, long totalRuntimeTicks, string segmentContainer, string endpointPrefix, string queryString, bool isRemuxingVideo)
+ public CreateMainPlaylistRequest(Guid? mediaSourceId, string filePath, int desiredSegmentLengthMs, long totalRuntimeTicks, string segmentContainer, string endpointPrefix, string queryString, bool isRemuxingVideo)
{
+ MediaSourceId = mediaSourceId;
FilePath = filePath;
DesiredSegmentLengthMs = desiredSegmentLengthMs;
TotalRuntimeTicks = totalRuntimeTicks;
@@ -27,6 +31,11 @@ public class CreateMainPlaylistRequest
}
/// <summary>
+ /// Gets the media source id.
+ /// </summary>
+ public Guid? MediaSourceId { get; }
+
+ /// <summary>
/// Gets the file path.
/// </summary>
public string FilePath { get; }
diff --git a/src/Jellyfin.MediaEncoding.Hls/Playlist/DynamicHlsPlaylistGenerator.cs b/src/Jellyfin.MediaEncoding.Hls/Playlist/DynamicHlsPlaylistGenerator.cs
index 1846ba26b..fb5027e5b 100644
--- a/src/Jellyfin.MediaEncoding.Hls/Playlist/DynamicHlsPlaylistGenerator.cs
+++ b/src/Jellyfin.MediaEncoding.Hls/Playlist/DynamicHlsPlaylistGenerator.cs
@@ -35,7 +35,9 @@ public class DynamicHlsPlaylistGenerator : IDynamicHlsPlaylistGenerator
{
IReadOnlyList<double> segments;
// For video transcodes it is sufficient with equal length segments as ffmpeg will create new keyframes
- if (request.IsRemuxingVideo && TryExtractKeyframes(request.FilePath, out var keyframeData))
+ if (request.IsRemuxingVideo
+ && request.MediaSourceId is not null
+ && TryExtractKeyframes(request.MediaSourceId.Value, request.FilePath, out var keyframeData))
{
segments = ComputeSegments(keyframeData, request.DesiredSegmentLengthMs);
}
@@ -104,7 +106,7 @@ public class DynamicHlsPlaylistGenerator : IDynamicHlsPlaylistGenerator
return builder.ToString();
}
- private bool TryExtractKeyframes(string filePath, [NotNullWhen(true)] out KeyframeData? keyframeData)
+ private bool TryExtractKeyframes(Guid itemId, string filePath, [NotNullWhen(true)] out KeyframeData? keyframeData)
{
keyframeData = null;
if (!IsExtractionAllowedForFile(filePath, _serverConfigurationManager.GetEncodingOptions().AllowOnDemandMetadataBasedKeyframeExtractionForExtensions))
@@ -116,7 +118,7 @@ public class DynamicHlsPlaylistGenerator : IDynamicHlsPlaylistGenerator
for (var i = 0; i < len; i++)
{
var extractor = _extractors[i];
- if (!extractor.TryExtractKeyframes(filePath, out var result))
+ if (!extractor.TryExtractKeyframes(itemId, filePath, out var result))
{
continue;
}
diff --git a/src/Jellyfin.MediaEncoding.Hls/ScheduledTasks/KeyframeExtractionScheduledTask.cs b/src/Jellyfin.MediaEncoding.Hls/ScheduledTasks/KeyframeExtractionScheduledTask.cs
index caf6a2aae..d63ee6777 100644
--- a/src/Jellyfin.MediaEncoding.Hls/ScheduledTasks/KeyframeExtractionScheduledTask.cs
+++ b/src/Jellyfin.MediaEncoding.Hls/ScheduledTasks/KeyframeExtractionScheduledTask.cs
@@ -9,7 +9,6 @@ using Jellyfin.MediaEncoding.Hls.Extractors;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Tasks;
@@ -23,7 +22,7 @@ public class KeyframeExtractionScheduledTask : IScheduledTask
private readonly ILocalizationManager _localizationManager;
private readonly ILibraryManager _libraryManager;
private readonly IKeyframeExtractor[] _keyframeExtractors;
- private static readonly BaseItemKind[] _itemTypes = { BaseItemKind.Episode, BaseItemKind.Movie };
+ private static readonly BaseItemKind[] _itemTypes = [BaseItemKind.Episode, BaseItemKind.Movie];
/// <summary>
/// Initializes a new instance of the <see cref="KeyframeExtractionScheduledTask"/> class.
@@ -55,11 +54,11 @@ public class KeyframeExtractionScheduledTask : IScheduledTask
{
var query = new InternalItemsQuery
{
- MediaTypes = new[] { MediaType.Video },
+ MediaTypes = [MediaType.Video],
IsVirtualItem = false,
IncludeItemTypes = _itemTypes,
DtoOptions = new DtoOptions(true),
- SourceTypes = new[] { SourceType.Library },
+ SourceTypes = [SourceType.Library],
Recursive = true,
Limit = Pagesize
};
@@ -74,19 +73,16 @@ public class KeyframeExtractionScheduledTask : IScheduledTask
query.StartIndex = startIndex;
var videos = _libraryManager.GetItemList(query);
- var currentPageCount = videos.Count;
- // TODO parallelize with Parallel.ForEach?
- for (var i = 0; i < currentPageCount; i++)
+ foreach (var video in videos)
{
- var video = videos[i];
// Only local files supported
- if (video.IsFileProtocol && File.Exists(video.Path))
+ var path = video.Path;
+ if (File.Exists(path))
{
- for (var j = 0; j < _keyframeExtractors.Length; j++)
+ foreach (var extractor in _keyframeExtractors)
{
- var extractor = _keyframeExtractors[j];
- // The cache decorator will make sure to save them in the data dir
- if (extractor.TryExtractKeyframes(video.Path, out _))
+ // The cache decorator will make sure to save the keyframes
+ if (extractor.TryExtractKeyframes(video.Id, path, out _))
{
break;
}
@@ -107,5 +103,5 @@ public class KeyframeExtractionScheduledTask : IScheduledTask
}
/// <inheritdoc />
- public IEnumerable<TaskTriggerInfo> GetDefaultTriggers() => Enumerable.Empty<TaskTriggerInfo>();
+ public IEnumerable<TaskTriggerInfo> GetDefaultTriggers() => [];
}
diff --git a/src/Jellyfin.MediaEncoding.Keyframes/Jellyfin.MediaEncoding.Keyframes.csproj b/src/Jellyfin.MediaEncoding.Keyframes/Jellyfin.MediaEncoding.Keyframes.csproj
index c826d3d9c..cc8d942eb 100644
--- a/src/Jellyfin.MediaEncoding.Keyframes/Jellyfin.MediaEncoding.Keyframes.csproj
+++ b/src/Jellyfin.MediaEncoding.Keyframes/Jellyfin.MediaEncoding.Keyframes.csproj
@@ -5,6 +5,19 @@
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
+ <PropertyGroup>
+ <Authors>Jellyfin Contributors</Authors>
+ <PackageId>Jellyfin.MediaEncoding.Keyframes</PackageId>
+ <VersionPrefix>10.11.0</VersionPrefix>
+ <RepositoryUrl>https://github.com/jellyfin/jellyfin</RepositoryUrl>
+ <PackageLicenseExpression>GPL-3.0-only</PackageLicenseExpression>
+ </PropertyGroup>
+
+ <PropertyGroup Condition=" '$(Stability)'=='Unstable'">
+ <!-- Include all symbols in the main nupkg until Azure Artifact Feed starts supporting ingesting NuGet symbol packages. -->
+ <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
+ </PropertyGroup>
+
<ItemGroup>
<PackageReference Include="NEbml" />
</ItemGroup>
diff --git a/src/Jellyfin.Networking/Manager/NetworkManager.cs b/src/Jellyfin.Networking/Manager/NetworkManager.cs
index 6f6ee5146..126d9f15c 100644
--- a/src/Jellyfin.Networking/Manager/NetworkManager.cs
+++ b/src/Jellyfin.Networking/Manager/NetworkManager.cs
@@ -7,6 +7,7 @@ using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;
+using J2N.Collections.Generic.Extensions;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
using MediaBrowser.Model.Net;
@@ -214,81 +215,92 @@ public class NetworkManager : INetworkManager, IDisposable
{
lock (_initLock)
{
- _logger.LogDebug("Refreshing interfaces.");
+ _interfaces = GetInterfacesCore(_logger, IsIPv4Enabled, IsIPv6Enabled).ToList();
+ }
+ }
- var interfaces = new List<IPData>();
+ /// <summary>
+ /// Generate a list of all the interface ip addresses and submasks where that are in the active/unknown state.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ /// <param name="isIPv4Enabled">If true evaluates IPV4 type ip addresses.</param>
+ /// <param name="isIPv6Enabled">If true evaluates IPV6 type ip addresses.</param>
+ /// <returns>A list of all locally known up addresses and submasks that are to be considered usable.</returns>
+ public static IReadOnlyList<IPData> GetInterfacesCore(ILogger logger, bool isIPv4Enabled, bool isIPv6Enabled)
+ {
+ logger.LogDebug("Refreshing interfaces.");
- try
- {
- var nics = NetworkInterface.GetAllNetworkInterfaces()
- .Where(i => i.OperationalStatus == OperationalStatus.Up);
+ var interfaces = new List<IPData>();
+
+ try
+ {
+ var nics = NetworkInterface.GetAllNetworkInterfaces()
+ .Where(i => i.OperationalStatus == OperationalStatus.Up);
- foreach (NetworkInterface adapter in nics)
+ foreach (NetworkInterface adapter in nics)
+ {
+ try
{
- try
- {
- var ipProperties = adapter.GetIPProperties();
+ var ipProperties = adapter.GetIPProperties();
- // Populate interface list
- foreach (var info in ipProperties.UnicastAddresses)
+ // Populate interface list
+ foreach (var info in ipProperties.UnicastAddresses)
+ {
+ if (isIPv4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork)
{
- if (IsIPv4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork)
+ var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength), adapter.Name)
{
- var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength), adapter.Name)
- {
- Index = ipProperties.GetIPv4Properties().Index,
- Name = adapter.Name,
- SupportsMulticast = adapter.SupportsMulticast
- };
-
- interfaces.Add(interfaceObject);
- }
- else if (IsIPv6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6)
+ Index = ipProperties.GetIPv4Properties().Index,
+ Name = adapter.Name,
+ SupportsMulticast = adapter.SupportsMulticast
+ };
+
+ interfaces.Add(interfaceObject);
+ }
+ else if (isIPv6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength), adapter.Name)
{
- var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength), adapter.Name)
- {
- Index = ipProperties.GetIPv6Properties().Index,
- Name = adapter.Name,
- SupportsMulticast = adapter.SupportsMulticast
- };
-
- interfaces.Add(interfaceObject);
- }
+ Index = ipProperties.GetIPv6Properties().Index,
+ Name = adapter.Name,
+ SupportsMulticast = adapter.SupportsMulticast
+ };
+
+ interfaces.Add(interfaceObject);
}
}
- catch (Exception ex)
- {
- // Ignore error, and attempt to continue.
- _logger.LogError(ex, "Error encountered parsing interfaces.");
- }
+ }
+ catch (Exception ex)
+ {
+ // Ignore error, and attempt to continue.
+ logger.LogError(ex, "Error encountered parsing interfaces.");
}
}
- catch (Exception ex)
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(ex, "Error obtaining interfaces.");
+ }
+
+ // If no interfaces are found, fallback to loopback interfaces.
+ if (interfaces.Count == 0)
+ {
+ logger.LogWarning("No interface information available. Using loopback interface(s).");
+
+ if (isIPv4Enabled)
{
- _logger.LogError(ex, "Error obtaining interfaces.");
+ interfaces.Add(new IPData(IPAddress.Loopback, NetworkConstants.IPv4RFC5735Loopback, "lo"));
}
- // If no interfaces are found, fallback to loopback interfaces.
- if (interfaces.Count == 0)
+ if (isIPv6Enabled)
{
- _logger.LogWarning("No interface information available. Using loopback interface(s).");
-
- if (IsIPv4Enabled)
- {
- interfaces.Add(new IPData(IPAddress.Loopback, NetworkConstants.IPv4RFC5735Loopback, "lo"));
- }
-
- if (IsIPv6Enabled)
- {
- interfaces.Add(new IPData(IPAddress.IPv6Loopback, NetworkConstants.IPv6RFC4291Loopback, "lo"));
- }
+ interfaces.Add(new IPData(IPAddress.IPv6Loopback, NetworkConstants.IPv6RFC4291Loopback, "lo"));
}
-
- _logger.LogDebug("Discovered {NumberOfInterfaces} interfaces.", interfaces.Count);
- _logger.LogDebug("Interfaces addresses: {Addresses}", interfaces.OrderByDescending(s => s.AddressFamily == AddressFamily.InterNetwork).Select(s => s.Address.ToString()));
-
- _interfaces = interfaces;
}
+
+ logger.LogDebug("Discovered {NumberOfInterfaces} interfaces.", interfaces.Count);
+ logger.LogDebug("Interfaces addresses: {Addresses}", interfaces.OrderByDescending(s => s.AddressFamily == AddressFamily.InterNetwork).Select(s => s.Address.ToString()));
+ return interfaces;
}
/// <summary>
@@ -345,64 +357,76 @@ public class NetworkManager : INetworkManager, IDisposable
{
lock (_initLock)
{
- // Respect explicit bind addresses
- var interfaces = _interfaces.ToList();
- var localNetworkAddresses = config.LocalNetworkAddresses;
- if (localNetworkAddresses.Length > 0 && !string.IsNullOrWhiteSpace(localNetworkAddresses[0]))
- {
- var bindAddresses = localNetworkAddresses.Select(p => NetworkUtils.TryParseToSubnet(p, out var network)
- ? network.Prefix
- : (interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase))
- .Select(x => x.Address)
- .FirstOrDefault() ?? IPAddress.None))
- .Where(x => x != IPAddress.None)
- .ToHashSet();
- interfaces = interfaces.Where(x => bindAddresses.Contains(x.Address)).ToList();
-
- if (bindAddresses.Contains(IPAddress.Loopback) && !interfaces.Any(i => i.Address.Equals(IPAddress.Loopback)))
- {
- interfaces.Add(new IPData(IPAddress.Loopback, NetworkConstants.IPv4RFC5735Loopback, "lo"));
- }
-
- if (bindAddresses.Contains(IPAddress.IPv6Loopback) && !interfaces.Any(i => i.Address.Equals(IPAddress.IPv6Loopback)))
- {
- interfaces.Add(new IPData(IPAddress.IPv6Loopback, NetworkConstants.IPv6RFC4291Loopback, "lo"));
- }
- }
+ _interfaces = FilterBindSettings(config, _interfaces, IsIPv4Enabled, IsIPv6Enabled).ToList();
+ }
+ }
- // Remove all interfaces matching any virtual machine interface prefix
- if (config.IgnoreVirtualInterfaces)
+ /// <summary>
+ /// Filteres a list of bind addresses and exclusions on available interfaces.
+ /// </summary>
+ /// <param name="config">The network config to be filtered by.</param>
+ /// <param name="interfaces">A list of possible interfaces to be filtered.</param>
+ /// <param name="isIPv4Enabled">If true evaluates IPV4 type ip addresses.</param>
+ /// <param name="isIPv6Enabled">If true evaluates IPV6 type ip addresses.</param>
+ /// <returns>A list of all locally known up addresses and submasks that are to be considered usable.</returns>
+ public static IReadOnlyList<IPData> FilterBindSettings(NetworkConfiguration config, IList<IPData> interfaces, bool isIPv4Enabled, bool isIPv6Enabled)
+ {
+ // Respect explicit bind addresses
+ var localNetworkAddresses = config.LocalNetworkAddresses;
+ if (localNetworkAddresses.Length > 0 && !string.IsNullOrWhiteSpace(localNetworkAddresses[0]))
+ {
+ var bindAddresses = localNetworkAddresses.Select(p => NetworkUtils.TryParseToSubnet(p, out var network)
+ ? network.Prefix
+ : (interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase))
+ .Select(x => x.Address)
+ .FirstOrDefault() ?? IPAddress.None))
+ .Where(x => x != IPAddress.None)
+ .ToHashSet();
+ interfaces = interfaces.Where(x => bindAddresses.Contains(x.Address)).ToList();
+
+ if (bindAddresses.Contains(IPAddress.Loopback) && !interfaces.Any(i => i.Address.Equals(IPAddress.Loopback)))
{
- // Remove potentially existing * and split config string into prefixes
- var virtualInterfacePrefixes = config.VirtualInterfaceNames
- .Select(i => i.Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase));
-
- // Check all interfaces for matches against the prefixes and remove them
- if (_interfaces.Count > 0)
- {
- foreach (var virtualInterfacePrefix in virtualInterfacePrefixes)
- {
- interfaces.RemoveAll(x => x.Name.StartsWith(virtualInterfacePrefix, StringComparison.OrdinalIgnoreCase));
- }
- }
+ interfaces.Add(new IPData(IPAddress.Loopback, NetworkConstants.IPv4RFC5735Loopback, "lo"));
}
- // Remove all IPv4 interfaces if IPv4 is disabled
- if (!IsIPv4Enabled)
+ if (bindAddresses.Contains(IPAddress.IPv6Loopback) && !interfaces.Any(i => i.Address.Equals(IPAddress.IPv6Loopback)))
{
- interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetwork);
+ interfaces.Add(new IPData(IPAddress.IPv6Loopback, NetworkConstants.IPv6RFC4291Loopback, "lo"));
}
+ }
+
+ // Remove all interfaces matching any virtual machine interface prefix
+ if (config.IgnoreVirtualInterfaces)
+ {
+ // Remove potentially existing * and split config string into prefixes
+ var virtualInterfacePrefixes = config.VirtualInterfaceNames
+ .Select(i => i.Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase));
- // Remove all IPv6 interfaces if IPv6 is disabled
- if (!IsIPv6Enabled)
+ // Check all interfaces for matches against the prefixes and remove them
+ if (interfaces.Count > 0)
{
- interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetworkV6);
+ foreach (var virtualInterfacePrefix in virtualInterfacePrefixes)
+ {
+ interfaces.RemoveAll(x => x.Name.StartsWith(virtualInterfacePrefix, StringComparison.OrdinalIgnoreCase));
+ }
}
+ }
- // Users may have complex networking configuration that multiple interfaces sharing the same IP address
- // Only return one IP for binding, and let the OS handle the rest
- _interfaces = interfaces.DistinctBy(iface => iface.Address).ToList();
+ // Remove all IPv4 interfaces if IPv4 is disabled
+ if (!isIPv4Enabled)
+ {
+ interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetwork);
+ }
+
+ // Remove all IPv6 interfaces if IPv6 is disabled
+ if (!isIPv6Enabled)
+ {
+ interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetworkV6);
}
+
+ // Users may have complex networking configuration that multiple interfaces sharing the same IP address
+ // Only return one IP for binding, and let the OS handle the rest
+ return interfaces.DistinctBy(iface => iface.Address).ToList();
}
/// <summary>
@@ -666,33 +690,42 @@ public class NetworkManager : INetworkManager, IDisposable
}
/// <inheritdoc/>
- public bool HasRemoteAccess(IPAddress remoteIP)
+ public RemoteAccessPolicyResult ShouldAllowServerAccess(IPAddress remoteIP)
{
var config = _configurationManager.GetNetworkConfiguration();
- if (config.EnableRemoteAccess)
+ if (IsInLocalNetwork(remoteIP))
{
- // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely.
- // If left blank, all remote addresses will be allowed.
- if (_remoteAddressFilter.Any() && !IsInLocalNetwork(remoteIP))
- {
- // remoteAddressFilter is a whitelist or blacklist.
- var matches = _remoteAddressFilter.Count(remoteNetwork => NetworkUtils.SubnetContainsAddress(remoteNetwork, remoteIP));
- if ((!config.IsRemoteIPFilterBlacklist && matches > 0)
- || (config.IsRemoteIPFilterBlacklist && matches == 0))
- {
- return true;
- }
-
- return false;
- }
+ return RemoteAccessPolicyResult.Allow;
}
- else if (!IsInLocalNetwork(remoteIP))
+
+ if (!config.EnableRemoteAccess)
{
// Remote not enabled. So everyone should be LAN.
- return false;
+ return RemoteAccessPolicyResult.RejectDueToRemoteAccessDisabled;
}
- return true;
+ if (!_remoteAddressFilter.Any())
+ {
+ // No filter on remote addresses, allow any of them.
+ return RemoteAccessPolicyResult.Allow;
+ }
+
+ // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely.
+ // If left blank, all remote addresses will be allowed.
+
+ // remoteAddressFilter is a whitelist or blacklist.
+ var anyMatches = _remoteAddressFilter.Any(remoteNetwork => NetworkUtils.SubnetContainsAddress(remoteNetwork, remoteIP));
+ if (config.IsRemoteIPFilterBlacklist)
+ {
+ return anyMatches
+ ? RemoteAccessPolicyResult.RejectDueToIPBlocklist
+ : RemoteAccessPolicyResult.Allow;
+ }
+
+ // Allow-list
+ return anyMatches
+ ? RemoteAccessPolicyResult.Allow
+ : RemoteAccessPolicyResult.RejectDueToNotAllowlistedRemoteIP;
}
/// <inheritdoc/>
@@ -720,28 +753,47 @@ public class NetworkManager : INetworkManager, IDisposable
/// <inheritdoc/>
public IReadOnlyList<IPData> GetAllBindInterfaces(bool individualInterfaces = false)
{
- var config = _configurationManager.GetNetworkConfiguration();
+ return NetworkManager.GetAllBindInterfaces(individualInterfaces, _configurationManager, _interfaces, IsIPv4Enabled, IsIPv6Enabled);
+ }
+
+ /// <summary>
+ /// Reads the jellyfin configuration of the configuration manager and produces a list of interfaces that should be bound.
+ /// </summary>
+ /// <param name="individualInterfaces">Defines that only known interfaces should be used.</param>
+ /// <param name="configurationManager">The ConfigurationManager.</param>
+ /// <param name="knownInterfaces">The known interfaces that gets returned if possible or instructed.</param>
+ /// <param name="readIpv4">Include IPV4 type interfaces.</param>
+ /// <param name="readIpv6">Include IPV6 type interfaces.</param>
+ /// <returns>A list of ip address of which jellyfin should bind to.</returns>
+ public static IReadOnlyList<IPData> GetAllBindInterfaces(
+ bool individualInterfaces,
+ IConfigurationManager configurationManager,
+ IReadOnlyList<IPData> knownInterfaces,
+ bool readIpv4,
+ bool readIpv6)
+ {
+ var config = configurationManager.GetNetworkConfiguration();
var localNetworkAddresses = config.LocalNetworkAddresses;
- if ((localNetworkAddresses.Length > 0 && !string.IsNullOrWhiteSpace(localNetworkAddresses[0]) && _interfaces.Count > 0) || individualInterfaces)
+ if ((localNetworkAddresses.Length > 0 && !string.IsNullOrWhiteSpace(localNetworkAddresses[0]) && knownInterfaces.Count > 0) || individualInterfaces)
{
- return _interfaces;
+ return knownInterfaces;
}
// No bind address and no exclusions, so listen on all interfaces.
var result = new List<IPData>();
- if (IsIPv4Enabled && IsIPv6Enabled)
+ if (readIpv4 && readIpv6)
{
// Kestrel source code shows it uses Sockets.DualMode - so this also covers IPAddress.Any by default
result.Add(new IPData(IPAddress.IPv6Any, NetworkConstants.IPv6Any));
}
- else if (IsIPv4Enabled)
+ else if (readIpv4)
{
result.Add(new IPData(IPAddress.Any, NetworkConstants.IPv4Any));
}
- else if (IsIPv6Enabled)
+ else if (readIpv6)
{
// Cannot use IPv6Any as Kestrel will bind to IPv4 addresses too.
- foreach (var iface in _interfaces)
+ foreach (var iface in knownInterfaces)
{
if (iface.AddressFamily == AddressFamily.InterNetworkV6)
{
diff --git a/tests/Jellyfin.Api.Tests/Controllers/SystemControllerTests.cs b/tests/Jellyfin.Api.Tests/Controllers/SystemControllerTests.cs
index dd84c1a18..8cb3cde2b 100644
--- a/tests/Jellyfin.Api.Tests/Controllers/SystemControllerTests.cs
+++ b/tests/Jellyfin.Api.Tests/Controllers/SystemControllerTests.cs
@@ -1,4 +1,5 @@
using Jellyfin.Api.Controllers;
+using Jellyfin.Server.Implementations.SystemBackupService;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using MediaBrowser.Model.IO;
diff --git a/tests/Jellyfin.Api.Tests/Controllers/UserControllerTests.cs b/tests/Jellyfin.Api.Tests/Controllers/UserControllerTests.cs
index a74dab5f2..e95df1635 100644
--- a/tests/Jellyfin.Api.Tests/Controllers/UserControllerTests.cs
+++ b/tests/Jellyfin.Api.Tests/Controllers/UserControllerTests.cs
@@ -87,7 +87,7 @@ public class UserControllerTests
Assert.Contains(
Validate(userPolicy), v =>
v.MemberNames.Contains("PasswordResetProviderId") &&
- v.ErrorMessage != null &&
+ v.ErrorMessage is not null &&
v.ErrorMessage.Contains("required", StringComparison.CurrentCultureIgnoreCase));
}
@@ -105,7 +105,7 @@ public class UserControllerTests
Assert.Contains(Validate(userPolicy), v =>
v.MemberNames.Contains("AuthenticationProviderId") &&
- v.ErrorMessage != null &&
+ v.ErrorMessage is not null &&
v.ErrorMessage.Contains("required", StringComparison.CurrentCultureIgnoreCase));
}
diff --git a/tests/Jellyfin.Extensions.Tests/FileHelperTests.cs b/tests/Jellyfin.Extensions.Tests/FileHelperTests.cs
new file mode 100644
index 000000000..fb6a5dd0a
--- /dev/null
+++ b/tests/Jellyfin.Extensions.Tests/FileHelperTests.cs
@@ -0,0 +1,23 @@
+using System.IO;
+using Xunit;
+
+namespace Jellyfin.Extensions.Tests;
+
+public static class FileHelperTests
+{
+ [Fact]
+ public static void CreateEmpty_Valid_Correct()
+ {
+ var path = Path.Join(Path.GetTempPath(), Path.GetRandomFileName());
+ var fileInfo = new FileInfo(path);
+
+ Assert.False(fileInfo.Exists);
+
+ FileHelper.CreateEmpty(path);
+
+ fileInfo.Refresh();
+ Assert.True(fileInfo.Exists);
+
+ File.Delete(path);
+ }
+}
diff --git a/tests/Jellyfin.LiveTv.Tests/Listings/XmlTvListingsProviderTests.cs b/tests/Jellyfin.LiveTv.Tests/Listings/XmlTvListingsProviderTests.cs
index 0fb7894e5..b71dc1520 100644
--- a/tests/Jellyfin.LiveTv.Tests/Listings/XmlTvListingsProviderTests.cs
+++ b/tests/Jellyfin.LiveTv.Tests/Listings/XmlTvListingsProviderTests.cs
@@ -54,7 +54,7 @@ public class XmlTvListingsProviderTests
Path = path
};
- var startDate = new DateTime(2022, 11, 4);
+ var startDate = new DateTime(2022, 11, 4, 0, 0, 0, DateTimeKind.Utc);
var programs = await _xmlTvListingsProvider.GetProgramsAsync(info, "3297", startDate, startDate.AddDays(1), CancellationToken.None);
var programsList = programs.ToList();
Assert.Single(programsList);
@@ -78,7 +78,7 @@ public class XmlTvListingsProviderTests
Path = path
};
- var startDate = new DateTime(2022, 11, 4);
+ var startDate = new DateTime(2022, 11, 4, 0, 0, 0, DateTimeKind.Utc);
var programs = await _xmlTvListingsProvider.GetProgramsAsync(info, "3297", startDate, startDate.AddDays(1), CancellationToken.None);
var programsList = programs.ToList();
Assert.Single(programsList);
diff --git a/tests/Jellyfin.LiveTv.Tests/Test Data/LiveTv/Listings/XmlTv/emptycategory.xml b/tests/Jellyfin.LiveTv.Tests/Test Data/LiveTv/Listings/XmlTv/emptycategory.xml
index dd4aa8977..487b02893 100644
--- a/tests/Jellyfin.LiveTv.Tests/Test Data/LiveTv/Listings/XmlTv/emptycategory.xml
+++ b/tests/Jellyfin.LiveTv.Tests/Test Data/LiveTv/Listings/XmlTv/emptycategory.xml
@@ -1,5 +1,5 @@
<tv date="20221104">
- <programme channel="3297" start="20221104130000 -0400" stop="20221105235959 -0400">
+ <programme channel="3297" start="20221104130000 +0000" stop="20221105235959 +0000">
<category lang="en" />
<category lang="en">sports</category>
</programme>
diff --git a/tests/Jellyfin.LiveTv.Tests/Test Data/LiveTv/Listings/XmlTv/notitle.xml b/tests/Jellyfin.LiveTv.Tests/Test Data/LiveTv/Listings/XmlTv/notitle.xml
index 5a5be7997..b3cef41f3 100644
--- a/tests/Jellyfin.LiveTv.Tests/Test Data/LiveTv/Listings/XmlTv/notitle.xml
+++ b/tests/Jellyfin.LiveTv.Tests/Test Data/LiveTv/Listings/XmlTv/notitle.xml
@@ -1,5 +1,5 @@
<tv date="20221104">
- <programme channel="3297" start="20221104130000 -0400" stop="20221105235959 -0400">
+ <programme channel="3297" start="20221104130000 +0000" stop="20221105235959 +0000">
<category lang="en">sports</category>
<episode-num system="original-air-date">2022-11-04 13:00:00</episode-num>
<icon height="" src="https://domain.tld/image.png" width=""/>
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs
index df51d39cb..94710a095 100644
--- a/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs
+++ b/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs
@@ -289,6 +289,40 @@ namespace Jellyfin.MediaEncoding.Tests.Probing
}
[Fact]
+ public void GetMediaInfo_VideoWithSingleFrameMjpeg_Success()
+ {
+ var bytes = File.ReadAllBytes("Test Data/Probing/video_single_frame_mjpeg.json");
+
+ var internalMediaInfoResult = JsonSerializer.Deserialize<InternalMediaInfoResult>(bytes, _jsonOptions);
+ MediaInfo res = _probeResultNormalizer.GetMediaInfo(internalMediaInfoResult, VideoType.VideoFile, false, "Test Data/Probing/video_interlaced.mp4", MediaProtocol.File);
+
+ Assert.Equal(3, res.MediaStreams.Count);
+
+ Assert.NotNull(res.VideoStream);
+ Assert.Equal(res.MediaStreams[0], res.VideoStream);
+ Assert.Equal(0, res.VideoStream.Index);
+ Assert.Equal("h264", res.VideoStream.Codec);
+ Assert.Equal("High", res.VideoStream.Profile);
+ Assert.Equal(MediaStreamType.Video, res.VideoStream.Type);
+ Assert.Equal(1080, res.VideoStream.Height);
+ Assert.Equal(1920, res.VideoStream.Width);
+ Assert.False(res.VideoStream.IsInterlaced);
+ Assert.Equal("16:9", res.VideoStream.AspectRatio);
+ Assert.Equal("yuv420p", res.VideoStream.PixelFormat);
+ Assert.Equal(42d, res.VideoStream.Level);
+ Assert.Equal(1, res.VideoStream.RefFrames);
+ Assert.True(res.VideoStream.IsAVC);
+ Assert.Equal(50f, res.VideoStream.RealFrameRate);
+ Assert.Equal("1/1000", res.VideoStream.TimeBase);
+ Assert.Equal(8, res.VideoStream.BitDepth);
+ Assert.True(res.VideoStream.IsDefault);
+
+ var mjpeg = res.MediaStreams[2];
+ Assert.NotNull(mjpeg);
+ Assert.Equal("mjpeg", mjpeg.Codec);
+ }
+
+ [Fact]
public void GetMediaInfo_MusicVideo_Success()
{
var bytes = File.ReadAllBytes("Test Data/Probing/music_video_metadata.json");
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/video_single_frame_mjpeg.json b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/video_single_frame_mjpeg.json
new file mode 100644
index 000000000..261f044bb
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/video_single_frame_mjpeg.json
@@ -0,0 +1,209 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "h264",
+ "codec_long_name": "H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10",
+ "profile": "High",
+ "codec_type": "video",
+ "codec_tag_string": "[0][0][0][0]",
+ "codec_tag": "0x0000",
+ "width": 1920,
+ "height": 1080,
+ "coded_width": 1920,
+ "coded_height": 1080,
+ "closed_captions": 0,
+ "film_grain": 0,
+ "has_b_frames": 0,
+ "sample_aspect_ratio": "1:1",
+ "display_aspect_ratio": "16:9",
+ "pix_fmt": "yuv420p",
+ "level": 42,
+ "chroma_location": "left",
+ "field_order": "progressive",
+ "refs": 1,
+ "is_avc": "true",
+ "nal_length_size": "4",
+ "r_frame_rate": "50/1",
+ "avg_frame_rate": "50/1",
+ "time_base": "1/1000",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "bits_per_raw_sample": "8",
+ "extradata_size": 55,
+ "disposition": {
+ "default": 1,
+ "dub": 0,
+ "original": 0,
+ "comment": 0,
+ "lyrics": 0,
+ "karaoke": 0,
+ "forced": 0,
+ "hearing_impaired": 0,
+ "visual_impaired": 0,
+ "clean_effects": 0,
+ "attached_pic": 0,
+ "timed_thumbnails": 0,
+ "non_diegetic": 0,
+ "captions": 0,
+ "descriptions": 0,
+ "metadata": 0,
+ "dependent": 0,
+ "still_image": 0
+ },
+ "tags": {
+ "language": "deu",
+ "HANDLER_NAME": "VideoHandler",
+ "VENDOR_ID": "[0][0][0][0]",
+ "BPS": "3950584",
+ "DURATION": "00:00:10.000000000",
+ "NUMBER_OF_FRAMES": "500",
+ "NUMBER_OF_BYTES": "4938231",
+ "_STATISTICS_WRITING_APP": "mkvpropedit v90.0 ('Hanging On') 64-bit",
+ "_STATISTICS_WRITING_DATE_UTC": "2025-04-19 10:37:57",
+ "_STATISTICS_TAGS": "BPS DURATION NUMBER_OF_FRAMES NUMBER_OF_BYTES"
+ }
+ },
+ {
+ "index": 1,
+ "codec_name": "aac",
+ "codec_long_name": "AAC (Advanced Audio Coding)",
+ "profile": "LC",
+ "codec_type": "audio",
+ "codec_tag_string": "[0][0][0][0]",
+ "codec_tag": "0x0000",
+ "sample_fmt": "fltp",
+ "sample_rate": "48000",
+ "channels": 2,
+ "channel_layout": "stereo",
+ "bits_per_sample": 0,
+ "initial_padding": 0,
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "time_base": "1/1000",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "extradata_size": 2,
+ "disposition": {
+ "default": 1,
+ "dub": 0,
+ "original": 0,
+ "comment": 0,
+ "lyrics": 0,
+ "karaoke": 0,
+ "forced": 0,
+ "hearing_impaired": 0,
+ "visual_impaired": 0,
+ "clean_effects": 0,
+ "attached_pic": 0,
+ "timed_thumbnails": 0,
+ "non_diegetic": 0,
+ "captions": 0,
+ "descriptions": 0,
+ "metadata": 0,
+ "dependent": 0,
+ "still_image": 0
+ },
+ "tags": {
+ "language": "deu",
+ "HANDLER_NAME": "SoundHandler",
+ "VENDOR_ID": "[0][0][0][0]",
+ "BPS": "255785",
+ "DURATION": "00:00:09.984000000",
+ "NUMBER_OF_FRAMES": "469",
+ "NUMBER_OF_BYTES": "319220",
+ "_STATISTICS_WRITING_APP": "mkvpropedit v90.0 ('Hanging On') 64-bit",
+ "_STATISTICS_WRITING_DATE_UTC": "2025-04-19 10:37:57",
+ "_STATISTICS_TAGS": "BPS DURATION NUMBER_OF_FRAMES NUMBER_OF_BYTES"
+ }
+ },
+ {
+ "index": 2,
+ "codec_name": "mjpeg",
+ "codec_long_name": "Motion JPEG",
+ "profile": "Baseline",
+ "codec_type": "video",
+ "codec_tag_string": "[0][0][0][0]",
+ "codec_tag": "0x0000",
+ "width": 960,
+ "height": 540,
+ "coded_width": 960,
+ "coded_height": 540,
+ "closed_captions": 0,
+ "film_grain": 0,
+ "has_b_frames": 0,
+ "sample_aspect_ratio": "1:1",
+ "display_aspect_ratio": "16:9",
+ "pix_fmt": "yuvj420p",
+ "level": -99,
+ "color_range": "pc",
+ "color_space": "bt470bg",
+ "chroma_location": "center",
+ "refs": 1,
+ "r_frame_rate": "1000/1",
+ "avg_frame_rate": "30000/1",
+ "time_base": "1/1000",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "bits_per_raw_sample": "8",
+ "disposition": {
+ "default": 0,
+ "dub": 0,
+ "original": 0,
+ "comment": 0,
+ "lyrics": 0,
+ "karaoke": 0,
+ "forced": 0,
+ "hearing_impaired": 0,
+ "visual_impaired": 0,
+ "clean_effects": 0,
+ "attached_pic": 0,
+ "timed_thumbnails": 0,
+ "non_diegetic": 0,
+ "captions": 0,
+ "descriptions": 0,
+ "metadata": 0,
+ "dependent": 0,
+ "still_image": 0
+ },
+ "tags": {
+ "BPS": "0",
+ "DURATION": "00:00:00.000011111",
+ "NUMBER_OF_FRAMES": "1",
+ "NUMBER_OF_BYTES": "155034",
+ "_STATISTICS_WRITING_APP": "mkvpropedit v90.0 ('Hanging On') 64-bit",
+ "_STATISTICS_WRITING_DATE_UTC": "2025-04-19 10:37:57",
+ "_STATISTICS_TAGS": "BPS DURATION NUMBER_OF_FRAMES NUMBER_OF_BYTES"
+ }
+ }
+ ],
+ "chapters": [],
+ "format": {
+ "filename": "file:broken_mkv_covers - 01x03 - statistics added using mkvpropedit.mkv",
+ "nb_streams": 3,
+ "nb_programs": 0,
+ "nb_stream_groups": 0,
+ "format_name": "matroska,webm",
+ "format_long_name": "Matroska / WebM",
+ "start_time": "0.000000",
+ "duration": "10.005000",
+ "size": "5425928",
+ "bit_rate": "4338573",
+ "probe_score": 100,
+ "tags": {
+ "title": "Folge 1: Jackpot Immobilie · Wie wir klug vererben",
+ "EPISODE_SORT": "1",
+ "MAJOR_BRAND": "isom",
+ "MINOR_VERSION": "512",
+ "COMPATIBLE_BRANDS": "isomiso2avc1mp41",
+ "DATE": "20250318",
+ "SEASON_NUMBER": "1",
+ "COMMENT": "https://www.ardmediathek.de/video/Y3JpZDovL2JyLmRlL2Jyb2FkY2FzdC8zZWFmYTcxOC1mZDJmLTRmZTMtYWE4Ny03ZjdlNWViNTk1NDhfb25saW5lYnJvYWRjYXN0",
+ "DESCRIPTION": "Jeder kennt es: Enge Familienmitglieder sprechen plötzlich nicht mehr miteinander, der Streit ums Erbe entzweit die Familie. Was steht im Testament? Kann sich die Erbengemeinschaft einigen? Wie läuft das mit der Erbschaftssteuer und was sagt das Erbrecht?\n\nDas \"Lohnt sich das?\"-Team hat zwei Familien gefunden, die das Tabu rund ums Erben brechen. Sie erzählen, um wie viel Geld es geht, aber auch, was dieses Immobilienerbe mit ihrer Familie gemacht hat. Warum es einmal gelingt, Häuser in Millionenhöhe ohne jegliche Erbschaftssteuer zu vererben, während andere Geschwister sich über ihr Elternhaus komplett zerstritten haben. Erbfolge, Freibeträge, Nießbrauch - für alle Basics rund ums Erben ist Ralph Caspers zuständig, der kompetent erklärt. ",
+ "SYNOPSIS": "Jeder kennt es: Enge Familienmitglieder sprechen plötzlich nicht mehr miteinander, der Streit ums Erbe entzweit die Familie. Was steht im Testament? Kann sich die Erbengemeinschaft einigen? Wie läuft das mit der Erbschaftssteuer und was sagt das Erbrecht?\n\nDas \"Lohnt sich das?\"-Team hat zwei Familien gefunden, die das Tabu rund ums Erben brechen. Sie erzählen, um wie viel Geld es geht, aber auch, was dieses Immobilienerbe mit ihrer Familie gemacht hat. Warum es einmal gelingt, Häuser in Millionenhöhe ohne jegliche Erbschaftssteuer zu vererben, während andere Geschwister sich über ihr Elternhaus komplett zerstritten haben. Erbfolge, Freibeträge, Nießbrauch - für alle Basics rund ums Erben ist Ralph Caspers zuständig, der kompetent erklärt. ",
+ "SHOW": "Generation Wohnkrise. Lohnt sich das?",
+ "EPISODE_ID": "Folge 1: Jackpot Immobilie · Wie wir klug vererben",
+ "ENCODER": "Lavf61.7.100"
+ }
+ }
+}
diff --git a/tests/Jellyfin.Model.Tests/Dlna/LegacyStreamInfo.cs b/tests/Jellyfin.Model.Tests/Dlna/LegacyStreamInfo.cs
index 981287c03..e32baef55 100644
--- a/tests/Jellyfin.Model.Tests/Dlna/LegacyStreamInfo.cs
+++ b/tests/Jellyfin.Model.Tests/Dlna/LegacyStreamInfo.cs
@@ -92,7 +92,7 @@ public class LegacyStreamInfo : StreamInfo
private static List<NameValuePair> BuildParams(StreamInfo item, string? accessToken)
{
- var list = new List<NameValuePair>();
+ List<NameValuePair> list = [];
string audioCodecs = item.AudioCodecs.Count == 0 ?
string.Empty :
@@ -109,7 +109,7 @@ public class LegacyStreamInfo : StreamInfo
list.Add(new NameValuePair("VideoCodec", videoCodecs));
list.Add(new NameValuePair("AudioCodec", audioCodecs));
list.Add(new NameValuePair("AudioStreamIndex", item.AudioStreamIndex.HasValue ? item.AudioStreamIndex.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
- list.Add(new NameValuePair("SubtitleStreamIndex", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod != SubtitleDeliveryMethod.External ? item.SubtitleStreamIndex.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
+ list.Add(new NameValuePair("SubtitleStreamIndex", item.SubtitleStreamIndex.HasValue && (item.AlwaysBurnInSubtitleWhenTranscoding || item.SubtitleDeliveryMethod != SubtitleDeliveryMethod.External) ? item.SubtitleStreamIndex.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
list.Add(new NameValuePair("VideoBitrate", item.VideoBitrate.HasValue ? item.VideoBitrate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
list.Add(new NameValuePair("AudioBitrate", item.AudioBitrate.HasValue ? item.AudioBitrate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
list.Add(new NameValuePair("AudioSampleRate", item.AudioSampleRate.HasValue ? item.AudioSampleRate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
@@ -182,25 +182,16 @@ public class LegacyStreamInfo : StreamInfo
list.Add(new NameValuePair("CopyTimestamps", item.CopyTimestamps.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
}
- if (item.RequireAvc)
- {
- list.Add(new NameValuePair("RequireAvc", item.RequireAvc.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
- }
+ list.Add(new NameValuePair("RequireAvc", item.RequireAvc.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
- if (item.EnableAudioVbrEncoding)
- {
- list.Add(new NameValuePair("EnableAudioVbrEncoding", item.EnableAudioVbrEncoding.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
- }
+ list.Add(new NameValuePair("EnableAudioVbrEncoding", item.EnableAudioVbrEncoding.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
}
list.Add(new NameValuePair("Tag", item.MediaSource?.ETag ?? string.Empty));
- string subtitleCodecs = item.SubtitleCodecs.Count == 0 ?
- string.Empty :
- string.Join(",", item.SubtitleCodecs);
-
- list.Add(new NameValuePair("SubtitleMethod", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod != SubtitleDeliveryMethod.External ? item.SubtitleDeliveryMethod.ToString() : string.Empty));
+ string subtitleCodecs = item.SubtitleCodecs.Count == 0 ? string.Empty : string.Join(",", item.SubtitleCodecs);
list.Add(new NameValuePair("SubtitleCodec", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Embed ? subtitleCodecs : string.Empty));
+ list.Add(new NameValuePair("SubtitleMethod", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod != SubtitleDeliveryMethod.External ? item.SubtitleDeliveryMethod.ToString() : string.Empty));
foreach (var pair in item.StreamOptions)
{
diff --git a/tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs b/tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs
index ae9edd386..2c1080ffe 100644
--- a/tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs
+++ b/tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs
@@ -182,6 +182,10 @@ namespace Jellyfin.Model.Tests
[InlineData("Tizen3-stereo", "mkv-vp9-aac-srt-2600k", PlayMethod.DirectPlay)]
[InlineData("Tizen3-stereo", "mkv-vp9-ac3-srt-2600k", PlayMethod.DirectPlay)]
[InlineData("Tizen3-stereo", "mkv-vp9-vorbis-vtt-2600k", PlayMethod.DirectPlay)]
+ [InlineData("Tizen3-stereo", "mkv-dvhe.08-eac3-15200k", PlayMethod.DirectPlay)]
+ [InlineData("Tizen3-stereo", "mp4-dvh1.05-eac3-15200k", PlayMethod.Transcode, TranscodeReason.VideoRangeTypeNotSupported | TranscodeReason.AudioChannelsNotSupported, "Transcode")]
+ [InlineData("Tizen3-stereo", "mp4-dvhe.08-eac3-15200k", PlayMethod.DirectPlay)]
+ [InlineData("Tizen3-stereo", "mkv-dvhe.05-eac3-28000k", PlayMethod.Transcode, TranscodeReason.VideoBitrateNotSupported | TranscodeReason.VideoRangeTypeNotSupported | TranscodeReason.AudioChannelsNotSupported, "Transcode")]
[InlineData("Tizen3-stereo", "numstreams-32", PlayMethod.DirectPlay)]
[InlineData("Tizen3-stereo", "numstreams-33", PlayMethod.Transcode, TranscodeReason.StreamCountExceedsLimit, "Remux")]
// Tizen 4 4K 5.1
@@ -195,6 +199,10 @@ namespace Jellyfin.Model.Tests
[InlineData("Tizen4-4K-5.1", "mkv-vp9-aac-srt-2600k", PlayMethod.DirectPlay)]
[InlineData("Tizen4-4K-5.1", "mkv-vp9-ac3-srt-2600k", PlayMethod.DirectPlay)]
[InlineData("Tizen4-4K-5.1", "mkv-vp9-vorbis-vtt-2600k", PlayMethod.DirectPlay)]
+ [InlineData("Tizen4-4K-5.1", "mkv-dvhe.08-eac3-15200k", PlayMethod.DirectPlay)]
+ [InlineData("Tizen4-4K-5.1", "mp4-dvh1.05-eac3-15200k", PlayMethod.Transcode, TranscodeReason.VideoRangeTypeNotSupported, "Transcode")]
+ [InlineData("Tizen4-4K-5.1", "mp4-dvhe.08-eac3-15200k", PlayMethod.DirectPlay)]
+ [InlineData("Tizen4-4K-5.1", "mkv-dvhe.05-eac3-28000k", PlayMethod.Transcode, TranscodeReason.VideoRangeTypeNotSupported, "Transcode")]
[InlineData("Tizen4-4K-5.1", "numstreams-32", PlayMethod.DirectPlay)]
[InlineData("Tizen4-4K-5.1", "numstreams-33", PlayMethod.Transcode, TranscodeReason.StreamCountExceedsLimit, "Remux")]
// WebOS 23
diff --git a/tests/Jellyfin.Model.Tests/Dlna/StreamInfoTests.cs b/tests/Jellyfin.Model.Tests/Dlna/StreamInfoTests.cs
index 86819de8c..8dea46806 100644
--- a/tests/Jellyfin.Model.Tests/Dlna/StreamInfoTests.cs
+++ b/tests/Jellyfin.Model.Tests/Dlna/StreamInfoTests.cs
@@ -31,7 +31,7 @@ public class StreamInfoTests
/// <returns>An <see cref="Array"/> of <see cref="Type"/>.</returns>
private static object? RandomArray(Random random, Type? elementType)
{
- if (elementType == null)
+ if (elementType is null)
{
return null;
}
@@ -148,7 +148,7 @@ public class StreamInfoTests
var type = property.PropertyType;
// If nullable, then set it to null, 25% of the time.
- if (Nullable.GetUnderlyingType(type) != null)
+ if (Nullable.GetUnderlyingType(type) is not null)
{
if (random.Next(0, 4) == 0)
{
diff --git a/tests/Jellyfin.Model.Tests/Test Data/DeviceProfile-Tizen3-stereo.json b/tests/Jellyfin.Model.Tests/Test Data/DeviceProfile-Tizen3-stereo.json
index 895d13f07..9d43d2166 100644
--- a/tests/Jellyfin.Model.Tests/Test Data/DeviceProfile-Tizen3-stereo.json
+++ b/tests/Jellyfin.Model.Tests/Test Data/DeviceProfile-Tizen3-stereo.json
@@ -439,7 +439,14 @@
{
"Condition": "EqualsAny",
"Property": "VideoProfile",
- "Value": "high|main|baseline|constrained baseline|high 10",
+ "Value": "high|main|baseline|constrained baseline",
+ "IsRequired": false,
+ "$type": "ProfileCondition"
+ },
+ {
+ "Condition": "EqualsAny",
+ "Property": "VideoRangeType",
+ "Value": "SDR",
"IsRequired": false,
"$type": "ProfileCondition"
},
@@ -479,6 +486,13 @@
"$type": "ProfileCondition"
},
{
+ "Condition": "EqualsAny",
+ "Property": "VideoRangeType",
+ "Value": "SDR|DOVIWithSDR|HDR10|DOVIWithHDR10|HLG|DOVIWithHLG",
+ "IsRequired": false,
+ "$type": "ProfileCondition"
+ },
+ {
"Condition": "LessThanEqual",
"Property": "VideoLevel",
"Value": "183",
diff --git a/tests/Jellyfin.Model.Tests/Test Data/DeviceProfile-Tizen4-4K-5.1.json b/tests/Jellyfin.Model.Tests/Test Data/DeviceProfile-Tizen4-4K-5.1.json
index 345d38725..3859ef994 100644
--- a/tests/Jellyfin.Model.Tests/Test Data/DeviceProfile-Tizen4-4K-5.1.json
+++ b/tests/Jellyfin.Model.Tests/Test Data/DeviceProfile-Tizen4-4K-5.1.json
@@ -439,7 +439,14 @@
{
"Condition": "EqualsAny",
"Property": "VideoProfile",
- "Value": "high|main|baseline|constrained baseline|high 10",
+ "Value": "high|main|baseline|constrained baseline",
+ "IsRequired": false,
+ "$type": "ProfileCondition"
+ },
+ {
+ "Condition": "EqualsAny",
+ "Property": "VideoRangeType",
+ "Value": "SDR",
"IsRequired": false,
"$type": "ProfileCondition"
},
@@ -472,6 +479,13 @@
"$type": "ProfileCondition"
},
{
+ "Condition": "EqualsAny",
+ "Property": "VideoRangeType",
+ "Value": "SDR|DOVIWithSDR|HDR10|DOVIWithHDR10|HLG|DOVIWithHLG",
+ "IsRequired": false,
+ "$type": "ProfileCondition"
+ },
+ {
"Condition": "LessThanEqual",
"Property": "VideoLevel",
"Value": "183",
diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs
index 4144300da..38208476f 100644
--- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs
+++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs
@@ -79,7 +79,10 @@ namespace Jellyfin.Networking.Tests
[InlineData("[fe80::7add:12ff:febb:c67b%16]")]
[InlineData("fd23:184f:2029:0:3139:7386:67d7:d517/56")]
public static void TryParseValidIPStringsTrue(string address)
- => Assert.True(NetworkUtils.TryParseToSubnet(address, out _));
+ {
+ Assert.True(NetworkUtils.TryParseToSubnet(address, out _));
+ Assert.True(NetworkUtils.TryParseToSubnet('!' + address, out _, true));
+ }
/// <summary>
/// Checks invalid IP address formats.
@@ -278,17 +281,40 @@ namespace Jellyfin.Networking.Tests
}
[Theory]
- [InlineData("185.10.10.10,200.200.200.200", "79.2.3.4", true)]
- [InlineData("185.10.10.10", "185.10.10.10", false)]
- [InlineData("", "100.100.100.100", false)]
+ [InlineData("185.10.10.10,200.200.200.200", "79.2.3.4", RemoteAccessPolicyResult.RejectDueToNotAllowlistedRemoteIP)]
+ [InlineData("185.10.10.10", "185.10.10.10", RemoteAccessPolicyResult.Allow)]
+ [InlineData("", "100.100.100.100", RemoteAccessPolicyResult.Allow)]
+
+ public void HasRemoteAccess_GivenWhitelist_AllowsOnlyIPsInWhitelist(string addresses, string remoteIP, RemoteAccessPolicyResult expectedResult)
+ {
+ // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely.
+ // If left blank, all remote addresses will be allowed.
+ var conf = new NetworkConfiguration()
+ {
+ EnableIPv4 = true,
+ RemoteIPFilter = addresses.Split(','),
+ IsRemoteIPFilterBlacklist = false
+ };
+
+ var startupConf = new Mock<IConfiguration>();
+ using var nm = new NetworkManager(NetworkParseTests.GetMockConfig(conf), startupConf.Object, new NullLogger<NetworkManager>());
+
+ Assert.Equal(expectedResult, nm.ShouldAllowServerAccess(IPAddress.Parse(remoteIP)));
+ }
+
+ [Theory]
+ [InlineData("185.10.10.10,200.200.200.200", "79.2.3.4", RemoteAccessPolicyResult.RejectDueToRemoteAccessDisabled)]
+ [InlineData("185.10.10.10", "127.0.0.1", RemoteAccessPolicyResult.Allow)]
+ [InlineData("", "100.100.100.100", RemoteAccessPolicyResult.RejectDueToRemoteAccessDisabled)]
- public void HasRemoteAccess_GivenWhitelist_AllowsOnlyIPsInWhitelist(string addresses, string remoteIP, bool denied)
+ public void HasRemoteAccess_GivenRemoteAccessDisabled_IgnoresAllowlist(string addresses, string remoteIP, RemoteAccessPolicyResult expectedResult)
{
// Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely.
// If left blank, all remote addresses will be allowed.
var conf = new NetworkConfiguration()
{
EnableIPv4 = true,
+ EnableRemoteAccess = false,
RemoteIPFilter = addresses.Split(','),
IsRemoteIPFilterBlacklist = false
};
@@ -296,15 +322,15 @@ namespace Jellyfin.Networking.Tests
var startupConf = new Mock<IConfiguration>();
using var nm = new NetworkManager(NetworkParseTests.GetMockConfig(conf), startupConf.Object, new NullLogger<NetworkManager>());
- Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIP)), denied);
+ Assert.Equal(expectedResult, nm.ShouldAllowServerAccess(IPAddress.Parse(remoteIP)));
}
[Theory]
- [InlineData("185.10.10.10", "79.2.3.4", false)]
- [InlineData("185.10.10.10", "185.10.10.10", true)]
- [InlineData("", "100.100.100.100", false)]
+ [InlineData("185.10.10.10", "79.2.3.4", RemoteAccessPolicyResult.Allow)]
+ [InlineData("185.10.10.10", "185.10.10.10", RemoteAccessPolicyResult.RejectDueToIPBlocklist)]
+ [InlineData("", "100.100.100.100", RemoteAccessPolicyResult.Allow)]
- public void HasRemoteAccess_GivenBlacklist_BlacklistTheIPs(string addresses, string remoteIP, bool denied)
+ public void HasRemoteAccess_GivenBlacklist_BlacklistTheIPs(string addresses, string remoteIP, RemoteAccessPolicyResult expectedResult)
{
// Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely.
// If left blank, all remote addresses will be allowed.
@@ -318,7 +344,7 @@ namespace Jellyfin.Networking.Tests
var startupConf = new Mock<IConfiguration>();
using var nm = new NetworkManager(NetworkParseTests.GetMockConfig(conf), startupConf.Object, new NullLogger<NetworkManager>());
- Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIP)), denied);
+ Assert.Equal(expectedResult, nm.ShouldAllowServerAccess(IPAddress.Parse(remoteIP)));
}
[Theory]
diff --git a/tests/Jellyfin.Providers.Tests/Lyrics/LrcLyricParserTests.cs b/tests/Jellyfin.Providers.Tests/Lyrics/LrcLyricParserTests.cs
new file mode 100644
index 000000000..756a688ab
--- /dev/null
+++ b/tests/Jellyfin.Providers.Tests/Lyrics/LrcLyricParserTests.cs
@@ -0,0 +1,41 @@
+using System.IO;
+using MediaBrowser.Model.Lyrics;
+using MediaBrowser.Providers.Lyric;
+using Xunit;
+
+namespace Jellyfin.Providers.Tests.Lyrics;
+
+public static class LrcLyricParserTests
+{
+ [Fact]
+ public static void ParseElrcCues()
+ {
+ var parser = new LrcLyricParser();
+ var fileContents = File.ReadAllText(Path.Combine("Test Data", "Lyrics", "Fleetwood Mac - Rumors.elrc"));
+ var parsed = parser.ParseLyrics(new LyricFile("Fleetwood Mac - Rumors.elrc", fileContents));
+
+ Assert.NotNull(parsed);
+ Assert.Equal(31, parsed.Lyrics.Count);
+
+ var line1 = parsed.Lyrics[0];
+ Assert.Equal("Every night that goes between", line1.Text);
+ Assert.NotNull(line1.Cues);
+ Assert.Equal(9, line1.Cues.Count);
+ Assert.Equal(68400000, line1.Cues[0].Start);
+ Assert.Equal(72000000, line1.Cues[0].End);
+
+ var line5 = parsed.Lyrics[4];
+ Assert.Equal("Every night you do not come", line5.Text);
+ Assert.NotNull(line5.Cues);
+ Assert.Equal(11, line5.Cues.Count);
+ Assert.Equal(377300000, line5.Cues[5].Start);
+ Assert.Equal(380000000, line5.Cues[5].End);
+
+ var lastLine = parsed.Lyrics[^1];
+ Assert.Equal("I have always been a storm", lastLine.Text);
+ Assert.NotNull(lastLine.Cues);
+ Assert.Equal(11, lastLine.Cues.Count);
+ Assert.Equal(2358000000, lastLine.Cues[^1].Start);
+ Assert.Null(lastLine.Cues[^1].End);
+ }
+}
diff --git a/tests/Jellyfin.Providers.Tests/Manager/ProviderManagerTests.cs b/tests/Jellyfin.Providers.Tests/Manager/ProviderManagerTests.cs
index c227883b5..87e7a4b56 100644
--- a/tests/Jellyfin.Providers.Tests/Manager/ProviderManagerTests.cs
+++ b/tests/Jellyfin.Providers.Tests/Manager/ProviderManagerTests.cs
@@ -12,6 +12,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Lyrics;
+using MediaBrowser.Controller.MediaSegments;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Model.Configuration;
diff --git a/tests/Jellyfin.Providers.Tests/Test Data/Lyrics/Fleetwood Mac - Rumors.elrc b/tests/Jellyfin.Providers.Tests/Test Data/Lyrics/Fleetwood Mac - Rumors.elrc
new file mode 100644
index 000000000..1df264c90
--- /dev/null
+++ b/tests/Jellyfin.Providers.Tests/Test Data/Lyrics/Fleetwood Mac - Rumors.elrc
@@ -0,0 +1,31 @@
+[00:06.84] <00:06.84> Every <00:07.20> <00:07.56> night <00:07.87> <00:08.19> that <00:08.46> <00:08.79> goes <00:09.19> <00:09.59> between
+[00:14.69] <00:14.69> I <00:14.78> <00:14.87> feel <00:15.15> <00:15.44> a <00:15.54> <00:15.65> little <00:15.96> <00:16.28> less
+[00:20.98] <00:20.98> As <00:21.10> <00:21.22> you <00:21.27> <00:21.31> slowly <00:21.79> <00:22.27> go <00:22.57> <00:22.87> away <00:23.74> <00:24.19> from <00:24.51> <00:24.82> me
+[00:28.73] <00:28.73> This <00:28.91> <00:29.09> is <00:29.22> <00:29.36> only <00:29.75> <00:30.14> another <00:30.92> <00:31.25> test
+[00:36.11] <00:36.11> Every <00:36.44> <00:36.77> night <00:37.14> <00:37.52> you <00:37.73> <00:38.00> do <00:38.24> <00:38.48> not <00:38.93> <00:39.41> come
+[00:43.56] <00:43.56> Your <00:43.65> <00:43.74> softness <00:44.21> <00:44.69> fades <00:45.01> <00:45.33> away
+[00:50.29] <00:50.29> Did <00:50.42> <00:50.56> I <00:50.70> <00:50.85> ever <00:51.41> <00:51.97> really <00:52.48> <00:52.99> care <00:53.56> <00:53.86> that <00:54.09> <00:54.34> much
+[00:58.07] <00:58.07> Is <00:58.20> <00:58.34> there <00:58.48> <00:58.63> anything <00:59.44> <00:59.69> left <00:59.94> <01:00.20> to <01:00.30> <01:00.41> say?
+[01:05.59] <01:05.59> Every <01:06.58> <01:07.78> hour <01:08.05> <01:08.32> of <01:08.92> <01:09.97> fear <01:10.39> <01:10.81> I <01:11.41> <01:11.47> spend
+[01:13.84] <01:13.84> My <01:13.99> <01:14.14> body <01:14.57> <01:15.01> tries <01:15.32> <01:15.64> to <01:15.71> <01:15.79> cry
+[01:18.60] <01:18.60> Living <01:19.41> <01:20.79> through <01:21.12> <01:21.45> each <01:21.90> <01:23.13> empty <01:23.83> <01:24.54> night
+[01:27.51] <01:27.51> A <01:27.60> <01:27.69> deadly <01:28.12> <01:28.56> call <01:28.90> <01:29.25> inside
+[01:34.29] <01:34.29> I <01:34.39> <01:34.50> haven't <01:35.37> <01:35.64> felt <01:35.92> <01:36.21> this <01:36.34> <01:36.48> way <01:36.79> <01:37.11> I <01:37.35> <01:37.62> feel
+[01:42.11] <01:42.11> Since <01:42.27> <01:42.44> many <01:42.71> <01:42.98> a <01:43.08> <01:43.19> years <01:43.46> <01:43.85> ago
+[01:48.92] <01:48.92> But <01:49.08> <01:49.25> in <01:49.36> <01:49.48> those <01:49.78> <01:50.09> years <01:50.50> <01:50.92> and <01:51.07> <01:51.23> the <01:51.30> <01:51.38> lifetime's <01:51.99> <01:52.61> past
+[01:56.60] <01:56.60> I <01:56.69> <01:56.78> did <01:56.91> <01:57.05> not <01:57.50> <01:57.92> deal <01:58.22> <01:58.52> with <01:58.68> <01:58.85> the <01:58.91> <01:58.97> road
+[02:03.13] <02:03.13> And <02:03.25> <02:03.37> I <02:03.45> <02:03.55> did <02:03.68> <02:03.81> not <02:04.20> <02:04.60> deal <02:04.94> <02:05.29> with <02:05.45> <02:05.62> you, <02:05.90> <02:06.19> I <02:06.50> <02:06.82> know
+[02:10.95] <02:10.95> Though <02:11.11> <02:11.28> the <02:11.35> <02:11.43> love <02:11.79> <02:12.15> has <02:12.32> <02:12.39> always <02:13.06> <02:13.74> been
+[02:17.70] <02:17.70> So <02:17.91> <02:18.12> I <02:18.16> <02:18.21> search <02:18.55> <02:18.90> to <02:19.03> <02:19.17> find <02:19.51> <02:19.86> an <02:20.14> <02:20.43> answer <02:21.24> <02:21.71> there
+[02:25.72] <02:25.72> So <02:25.96> <02:26.20> I <02:26.39> <02:26.59> can <02:27.04> <02:27.19> truly <02:27.65> <02:28.12> win
+[02:33.02] <02:33.02> Every <02:34.04> <02:35.29> hour <02:35.77> <02:35.84> of <02:36.38> <02:37.43> fear <02:37.92> <02:38.42> I <02:38.69> <02:38.96> spend
+[02:41.35] <02:41.35> My <02:41.63> <02:41.91> body <02:42.35> <02:42.79> tries <02:43.09> <02:43.39> to <02:43.48> <02:43.57> cry
+[02:46.32] <02:46.32> Living <02:47.04> <02:48.54> through <02:48.88> <02:49.23> each <02:49.56> <02:50.85> empty <02:51.55> <02:52.26> night
+[02:55.06] <02:55.06> A <02:55.13> <02:55.21> deadly <02:55.64> <02:56.08> call <02:56.42> <02:56.77> inside
+[03:01.50] <03:01.50> So <03:01.74> <03:01.98> I <03:02.04> <03:02.10> try <03:02.42> <03:02.76> to <03:02.81> <03:02.87> say <03:03.45> <03:04.20> goodbye, <03:04.53> <03:04.86> my <03:05.02> <03:05.19> friend
+[03:09.09] <03:09.09> I'd <03:09.19> <03:09.30> like <03:09.42> <03:09.54> to <03:09.70> <03:09.87> leave <03:10.02> <03:10.17> you <03:10.29> <03:10.41> with <03:10.71> <03:10.89> something <03:11.32> <03:11.76> warm
+[03:16.25] <03:16.25> But <03:16.34> <03:16.43> never <03:16.77> <03:17.12> have <03:17.25> <03:17.38> I <03:17.44> <03:17.51> been <03:17.73> <03:17.96> a <03:18.14> <03:18.32> blue <03:18.62> <03:18.92> calm <03:19.58> <03:19.76> sea
+[03:24.18] <03:24.18> I <03:24.31> <03:24.45> have <03:24.57> <03:24.69> always <03:25.59> <03:28.02> been <03:28.19> <03:28.38> a <03:28.51> <03:28.65> storm
+[03:33.69] <03:33.69> Always <03:35.43> <03:36.99> been <03:37.18> <03:37.38> a <03:37.50> <03:37.62> storm
+[03:41.45] <03:41.45> Ooh, <03:41.99> <03:42.53> always <03:44.42> <03:45.86> been <03:46.05> <03:46.25> a <03:46.41> <03:46.58> storm
+[03:50.34] <03:50.34> I <03:50.49> <03:50.64> have <03:51.07> <03:51.51> always <03:53.31> <03:54.78> been <03:54.96> <03:55.14> a <03:55.47> <03:55.80> storm
diff --git a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs
index 95a5b8179..6997b51ac 100644
--- a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs
+++ b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs
@@ -5,83 +5,119 @@ using System.Runtime.InteropServices;
using AutoFixture;
using AutoFixture.AutoMoq;
using Emby.Server.Implementations.IO;
+using Jellyfin.Extensions;
using Xunit;
-namespace Jellyfin.Server.Implementations.Tests.IO
+namespace Jellyfin.Server.Implementations.Tests.IO;
+
+public class ManagedFileSystemTests
{
- public class ManagedFileSystemTests
+ private readonly IFixture _fixture;
+ private readonly ManagedFileSystem _sut;
+
+ public ManagedFileSystemTests()
+ {
+ _fixture = new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true });
+ _sut = _fixture.Create<ManagedFileSystem>();
+ }
+
+ [Fact]
+ public void MoveDirectory_SameFileSystem_Correct()
+ => MoveDirectoryInternal();
+
+ [SkippableFact]
+ public void MoveDirectory_DifferentFileSystem_Correct()
+ {
+ const string DestinationParent = "/dev/shm";
+
+ Skip.IfNot(Directory.Exists(DestinationParent));
+
+ MoveDirectoryInternal(DestinationParent);
+ }
+
+ internal void MoveDirectoryInternal(string? destinationParent = null)
{
- private readonly IFixture _fixture;
- private readonly ManagedFileSystem _sut;
-
- public ManagedFileSystemTests()
- {
- _fixture = new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true });
- _sut = _fixture.Create<ManagedFileSystem>();
- }
-
- [SkippableTheory]
- [InlineData("/Volumes/Library/Sample/Music/Playlists/", "../Beethoven/Misc/Moonlight Sonata.mp3", "/Volumes/Library/Sample/Music/Beethoven/Misc/Moonlight Sonata.mp3")]
- [InlineData("/Volumes/Library/Sample/Music/Playlists/", "../../Beethoven/Misc/Moonlight Sonata.mp3", "/Volumes/Library/Sample/Beethoven/Misc/Moonlight Sonata.mp3")]
- [InlineData("/Volumes/Library/Sample/Music/Playlists/", "Beethoven/Misc/Moonlight Sonata.mp3", "/Volumes/Library/Sample/Music/Playlists/Beethoven/Misc/Moonlight Sonata.mp3")]
- [InlineData("/Volumes/Library/Sample/Music/Playlists/", "/mnt/Beethoven/Misc/Moonlight Sonata.mp3", "/mnt/Beethoven/Misc/Moonlight Sonata.mp3")]
- public void MakeAbsolutePathCorrectlyHandlesRelativeFilePathsOnUnixLike(
- string folderPath,
- string filePath,
- string expectedAbsolutePath)
- {
- Skip.If(OperatingSystem.IsWindows());
-
- var generatedPath = _sut.MakeAbsolutePath(folderPath, filePath);
- Assert.Equal(expectedAbsolutePath, generatedPath);
- }
-
- [SkippableTheory]
- [InlineData(@"C:\\Volumes\Library\Sample\Music\Playlists\", @"..\Beethoven\Misc\Moonlight Sonata.mp3", @"C:\Volumes\Library\Sample\Music\Beethoven\Misc\Moonlight Sonata.mp3")]
- [InlineData(@"C:\\Volumes\Library\Sample\Music\Playlists\", @"..\..\Beethoven\Misc\Moonlight Sonata.mp3", @"C:\Volumes\Library\Sample\Beethoven\Misc\Moonlight Sonata.mp3")]
- [InlineData(@"C:\\Volumes\Library\Sample\Music\Playlists\", @"Beethoven\Misc\Moonlight Sonata.mp3", @"C:\Volumes\Library\Sample\Music\Playlists\Beethoven\Misc\Moonlight Sonata.mp3")]
- [InlineData(@"C:\\Volumes\Library\Sample\Music\Playlists\", @"D:\\Beethoven\Misc\Moonlight Sonata.mp3", @"D:\\Beethoven\Misc\Moonlight Sonata.mp3")]
- public void MakeAbsolutePathCorrectlyHandlesRelativeFilePathsOnWindows(
- string folderPath,
- string filePath,
- string expectedAbsolutePath)
- {
- Skip.If(!OperatingSystem.IsWindows());
-
- var generatedPath = _sut.MakeAbsolutePath(folderPath, filePath);
-
- Assert.Equal(expectedAbsolutePath, generatedPath);
- }
-
- [Theory]
- [InlineData("ValidFileName", "ValidFileName")]
- [InlineData("AC/DC", "AC DC")]
- [InlineData("Invalid\0", "Invalid ")]
- [InlineData("AC/DC\0KD/A", "AC DC KD A")]
- public void GetValidFilename_ReturnsValidFilename(string filename, string expectedFileName)
- {
- Assert.Equal(expectedFileName, _sut.GetValidFilename(filename));
- }
-
- [SkippableFact]
- public void GetFileInfo_DanglingSymlink_ExistsFalse()
- {
- Skip.If(OperatingSystem.IsWindows());
-
- string testFileDir = Path.Combine(Path.GetTempPath(), "jellyfin-test-data");
- string testFileName = Path.Combine(testFileDir, Path.GetRandomFileName() + "-danglingsym.link");
-
- Directory.CreateDirectory(testFileDir);
- Assert.Equal(0, symlink("thispathdoesntexist", testFileName));
- Assert.True(File.Exists(testFileName));
-
- var metadata = _sut.GetFileInfo(testFileName);
- Assert.False(metadata.Exists);
- }
-
- [SuppressMessage("Naming Rules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Have to")]
- [DllImport("libc", SetLastError = true, CharSet = CharSet.Ansi)]
- [DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)]
- private static extern int symlink(string target, string linkpath);
+ const string TempFile0 = "tempfile0";
+ const string TempFile1 = "tempfile1";
+
+ destinationParent ??= Path.GetTempPath();
+
+ var sourceDir = Directory.CreateTempSubdirectory();
+ var destinationDir = Path.Join(destinationParent, Path.GetRandomFileName());
+ FileHelper.CreateEmpty(Path.Join(sourceDir.FullName, TempFile0));
+ FileHelper.CreateEmpty(Path.Join(sourceDir.FullName, TempFile1));
+
+ _sut.MoveDirectory(sourceDir.FullName, destinationDir);
+
+ Assert.True(Directory.Exists(destinationDir));
+ Assert.True(File.Exists(Path.Join(destinationDir, TempFile0)));
+ Assert.True(File.Exists(Path.Join(destinationDir, TempFile1)));
+ Assert.False(Directory.Exists(sourceDir.FullName));
+
+ Directory.Delete(destinationDir, true);
}
+
+ [SkippableTheory]
+ [InlineData("/Volumes/Library/Sample/Music/Playlists/", "../Beethoven/Misc/Moonlight Sonata.mp3", "/Volumes/Library/Sample/Music/Beethoven/Misc/Moonlight Sonata.mp3")]
+ [InlineData("/Volumes/Library/Sample/Music/Playlists/", "../../Beethoven/Misc/Moonlight Sonata.mp3", "/Volumes/Library/Sample/Beethoven/Misc/Moonlight Sonata.mp3")]
+ [InlineData("/Volumes/Library/Sample/Music/Playlists/", "Beethoven/Misc/Moonlight Sonata.mp3", "/Volumes/Library/Sample/Music/Playlists/Beethoven/Misc/Moonlight Sonata.mp3")]
+ [InlineData("/Volumes/Library/Sample/Music/Playlists/", "/mnt/Beethoven/Misc/Moonlight Sonata.mp3", "/mnt/Beethoven/Misc/Moonlight Sonata.mp3")]
+ public void MakeAbsolutePathCorrectlyHandlesRelativeFilePathsOnUnixLike(
+ string folderPath,
+ string filePath,
+ string expectedAbsolutePath)
+ {
+ Skip.If(OperatingSystem.IsWindows());
+
+ var generatedPath = _sut.MakeAbsolutePath(folderPath, filePath);
+ Assert.Equal(expectedAbsolutePath, generatedPath);
+ }
+
+ [SkippableTheory]
+ [InlineData(@"C:\\Volumes\Library\Sample\Music\Playlists\", @"..\Beethoven\Misc\Moonlight Sonata.mp3", @"C:\Volumes\Library\Sample\Music\Beethoven\Misc\Moonlight Sonata.mp3")]
+ [InlineData(@"C:\\Volumes\Library\Sample\Music\Playlists\", @"..\..\Beethoven\Misc\Moonlight Sonata.mp3", @"C:\Volumes\Library\Sample\Beethoven\Misc\Moonlight Sonata.mp3")]
+ [InlineData(@"C:\\Volumes\Library\Sample\Music\Playlists\", @"Beethoven\Misc\Moonlight Sonata.mp3", @"C:\Volumes\Library\Sample\Music\Playlists\Beethoven\Misc\Moonlight Sonata.mp3")]
+ [InlineData(@"C:\\Volumes\Library\Sample\Music\Playlists\", @"D:\\Beethoven\Misc\Moonlight Sonata.mp3", @"D:\\Beethoven\Misc\Moonlight Sonata.mp3")]
+ public void MakeAbsolutePathCorrectlyHandlesRelativeFilePathsOnWindows(
+ string folderPath,
+ string filePath,
+ string expectedAbsolutePath)
+ {
+ Skip.IfNot(OperatingSystem.IsWindows());
+
+ var generatedPath = _sut.MakeAbsolutePath(folderPath, filePath);
+
+ Assert.Equal(expectedAbsolutePath, generatedPath);
+ }
+
+ [Theory]
+ [InlineData("ValidFileName", "ValidFileName")]
+ [InlineData("AC/DC", "AC DC")]
+ [InlineData("Invalid\0", "Invalid ")]
+ [InlineData("AC/DC\0KD/A", "AC DC KD A")]
+ public void GetValidFilename_ReturnsValidFilename(string filename, string expectedFileName)
+ {
+ Assert.Equal(expectedFileName, _sut.GetValidFilename(filename));
+ }
+
+ [SkippableFact]
+ public void GetFileInfo_DanglingSymlink_ExistsFalse()
+ {
+ Skip.If(OperatingSystem.IsWindows());
+
+ string testFileDir = Path.Combine(Path.GetTempPath(), "jellyfin-test-data");
+ string testFileName = Path.Combine(testFileDir, Path.GetRandomFileName() + "-danglingsym.link");
+
+ Directory.CreateDirectory(testFileDir);
+ Assert.Equal(0, symlink("thispathdoesntexist", testFileName));
+ Assert.True(File.Exists(testFileName));
+
+ var metadata = _sut.GetFileInfo(testFileName);
+ Assert.False(metadata.Exists);
+ }
+
+ [SuppressMessage("Naming Rules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Have to")]
+ [DllImport("libc", SetLastError = true, CharSet = CharSet.Ansi)]
+ [DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)]
+ private static extern int symlink(string target, string linkpath);
}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/DotIgnoreIgnoreRuleTest.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/DotIgnoreIgnoreRuleTest.cs
new file mode 100644
index 000000000..d677c9f09
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Library/DotIgnoreIgnoreRuleTest.cs
@@ -0,0 +1,30 @@
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.Library;
+
+public class DotIgnoreIgnoreRuleTest
+{
+ [Fact]
+ public void Test()
+ {
+ var ignore = new Ignore.Ignore();
+ ignore.Add("SPs");
+ Assert.True(ignore.IsIgnored("f:/cd/sps/ffffff.mkv"));
+ Assert.True(ignore.IsIgnored("cd/sps/ffffff.mkv"));
+ Assert.True(ignore.IsIgnored("/cd/sps/ffffff.mkv"));
+ }
+
+ [Fact]
+ public void TestNegatePattern()
+ {
+ var ignore = new Ignore.Ignore();
+ ignore.Add("SPs");
+ ignore.Add("!thebestshot.mkv");
+ Assert.True(ignore.IsIgnored("f:/cd/sps/ffffff.mkv"));
+ Assert.True(ignore.IsIgnored("cd/sps/ffffff.mkv"));
+ Assert.True(ignore.IsIgnored("/cd/sps/ffffff.mkv"));
+ Assert.True(!ignore.IsIgnored("f:/cd/sps/thebestshot.mkv"));
+ Assert.True(!ignore.IsIgnored("cd/sps/thebestshot.mkv"));
+ Assert.True(!ignore.IsIgnored("/cd/sps/thebestshot.mkv"));
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs
index 5babc9117..a7a1e5e81 100644
--- a/tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs
+++ b/tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs
@@ -1,6 +1,7 @@
using System;
using System.Linq;
using System.Threading.Tasks;
+using BitFaster.Caching;
using Emby.Server.Implementations.Localization;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Model.Configuration;
@@ -51,6 +52,30 @@ namespace Jellyfin.Server.Implementations.Tests.Localization
Assert.Contains("ger", germany.ThreeLetterISOLanguageNames);
}
+ [Fact]
+ public async Task TryGetISO6392TFromB_Success()
+ {
+ var localizationManager = Setup(new ServerConfiguration
+ {
+ UICulture = "de-DE"
+ });
+ await localizationManager.LoadAll();
+
+ string? isoT;
+
+ // Translation ger -> deu
+ Assert.True(localizationManager.TryGetISO6392TFromB("ger", out isoT));
+ Assert.Equal("deu", isoT);
+
+ // chi -> zho
+ Assert.True(localizationManager.TryGetISO6392TFromB("chi", out isoT));
+ Assert.Equal("zho", isoT);
+
+ // eng is already ISO 639-2/T
+ Assert.False(localizationManager.TryGetISO6392TFromB("eng", out isoT));
+ Assert.Null(isoT);
+ }
+
[Theory]
[InlineData("de")]
[InlineData("deu")]
@@ -88,7 +113,7 @@ namespace Jellyfin.Server.Implementations.Tests.Localization
var tvma = ratings.FirstOrDefault(x => x.Name.Equals("TV-MA", StringComparison.Ordinal));
Assert.NotNull(tvma);
- Assert.Equal(17, tvma!.Value);
+ Assert.Equal(17, tvma!.RatingScore!.Score);
}
[Fact]
@@ -105,47 +130,49 @@ namespace Jellyfin.Server.Implementations.Tests.Localization
var fsk = ratings.FirstOrDefault(x => x.Name.Equals("FSK-12", StringComparison.Ordinal));
Assert.NotNull(fsk);
- Assert.Equal(12, fsk!.Value);
+ Assert.Equal(12, fsk!.RatingScore!.Score);
}
[Theory]
- [InlineData("CA-R", "CA", 18)]
- [InlineData("FSK-16", "DE", 16)]
- [InlineData("FSK-18", "DE", 18)]
- [InlineData("FSK-18", "US", 18)]
- [InlineData("TV-MA", "US", 17)]
- [InlineData("XXX", "asdf", 1000)]
- [InlineData("Germany: FSK-18", "DE", 18)]
- [InlineData("Rated : R", "US", 17)]
- [InlineData("Rated: R", "US", 17)]
- [InlineData("Rated R", "US", 17)]
- [InlineData(" PG-13 ", "US", 13)]
- public async Task GetRatingLevel_GivenValidString_Success(string value, string countryCode, int expectedLevel)
+ [InlineData("CA-R", "CA", 18, 1)]
+ [InlineData("FSK-16", "DE", 16, null)]
+ [InlineData("FSK-18", "DE", 18, null)]
+ [InlineData("FSK-18", "US", 18, null)]
+ [InlineData("TV-MA", "US", 17, 1)]
+ [InlineData("XXX", "asdf", 1000, null)]
+ [InlineData("Germany: FSK-18", "DE", 18, null)]
+ [InlineData("Rated : R", "US", 17, 0)]
+ [InlineData("Rated: R", "US", 17, 0)]
+ [InlineData("Rated R", "US", 17, 0)]
+ [InlineData(" PG-13 ", "US", 13, 0)]
+ public async Task GetRatingLevel_GivenValidString_Success(string value, string countryCode, int? expectedScore, int? expectedSubScore)
{
var localizationManager = Setup(new ServerConfiguration()
{
MetadataCountryCode = countryCode
});
await localizationManager.LoadAll();
- var level = localizationManager.GetRatingLevel(value);
- Assert.NotNull(level);
- Assert.Equal(expectedLevel, level!);
+ var score = localizationManager.GetRatingScore(value);
+ Assert.NotNull(score);
+ Assert.Equal(expectedScore, score.Score);
+ Assert.Equal(expectedSubScore, score.SubScore);
}
[Theory]
- [InlineData("0", 0)]
- [InlineData("1", 1)]
- [InlineData("6", 6)]
- [InlineData("12", 12)]
- [InlineData("42", 42)]
- [InlineData("9999", 9999)]
- public async Task GetRatingLevel_GivenValidAge_Success(string value, int expectedLevel)
+ [InlineData("0", 0, null)]
+ [InlineData("1", 1, null)]
+ [InlineData("6", 6, null)]
+ [InlineData("12", 12, null)]
+ [InlineData("42", 42, null)]
+ [InlineData("9999", 9999, null)]
+ public async Task GetRatingLevel_GivenValidAge_Success(string value, int? expectedScore, int? expectedSubScore)
{
var localizationManager = Setup(new ServerConfiguration { MetadataCountryCode = "nl" });
await localizationManager.LoadAll();
- var level = localizationManager.GetRatingLevel(value);
- Assert.NotNull(level);
- Assert.Equal(expectedLevel, level);
+ var score = localizationManager.GetRatingScore(value);
+ Assert.NotNull(score);
+ Assert.Equal(expectedScore, score.Score);
+ Assert.Equal(expectedSubScore, score.SubScore);
}
[Fact]
@@ -156,10 +183,10 @@ namespace Jellyfin.Server.Implementations.Tests.Localization
UICulture = "de-DE"
});
await localizationManager.LoadAll();
- Assert.Null(localizationManager.GetRatingLevel("NR"));
- Assert.Null(localizationManager.GetRatingLevel("unrated"));
- Assert.Null(localizationManager.GetRatingLevel("Not Rated"));
- Assert.Null(localizationManager.GetRatingLevel("n/a"));
+ Assert.Null(localizationManager.GetRatingScore("NR"));
+ Assert.Null(localizationManager.GetRatingScore("unrated"));
+ Assert.Null(localizationManager.GetRatingScore("Not Rated"));
+ Assert.Null(localizationManager.GetRatingScore("n/a"));
}
[Theory]
@@ -173,7 +200,7 @@ namespace Jellyfin.Server.Implementations.Tests.Localization
});
await localizationManager.LoadAll();
- Assert.Null(localizationManager.GetRatingLevel(value));
+ Assert.Null(localizationManager.GetRatingScore(value));
}
[Theory]
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Playlists/PlaylistManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Playlists/PlaylistManagerTests.cs
new file mode 100644
index 000000000..cc8ca720e
--- /dev/null
+++ b/tests/Jellyfin.Server.Implementations.Tests/Playlists/PlaylistManagerTests.cs
@@ -0,0 +1,40 @@
+using Emby.Server.Implementations.Playlists;
+using Xunit;
+
+namespace Jellyfin.Server.Implementations.Tests.Playlists;
+
+public class PlaylistManagerTests
+{
+ [Fact]
+ public void DetermineAdjustedIndexMoveToFirstPositionNoPriorInAllList()
+ {
+ var priorIndexAllChildren = 0;
+ var newIndex = 0;
+
+ var adjustedIndex = PlaylistManager.DetermineAdjustedIndex(priorIndexAllChildren, newIndex);
+
+ Assert.Equal(0, adjustedIndex);
+ }
+
+ [Fact]
+ public void DetermineAdjustedIndexPriorInMiddleOfAllList()
+ {
+ var priorIndexAllChildren = 2;
+ var newIndex = 0;
+
+ var adjustedIndex = PlaylistManager.DetermineAdjustedIndex(priorIndexAllChildren, newIndex);
+
+ Assert.Equal(1, adjustedIndex);
+ }
+
+ [Fact]
+ public void DetermineAdjustedIndexMoveMiddleOfPlaylist()
+ {
+ var priorIndexAllChildren = 2;
+ var newIndex = 1;
+
+ var adjustedIndex = PlaylistManager.DetermineAdjustedIndex(priorIndexAllChildren, newIndex);
+
+ Assert.Equal(3, adjustedIndex);
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs
index 934024826..b289c763b 100644
--- a/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs
+++ b/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs
@@ -6,6 +6,7 @@ using System.Threading.Tasks;
using AutoFixture;
using Emby.Server.Implementations.Library;
using Emby.Server.Implementations.Plugins;
+using Jellyfin.Extensions;
using Jellyfin.Extensions.Json;
using Jellyfin.Extensions.Json.Converters;
using MediaBrowser.Common.Plugins;
@@ -85,7 +86,7 @@ namespace Jellyfin.Server.Implementations.Tests.Plugins
var dllPath = Path.GetDirectoryName(Path.Combine(_pluginPath, dllFile))!;
Directory.CreateDirectory(dllPath);
- File.Create(Path.Combine(dllPath, filename));
+ FileHelper.CreateEmpty(Path.Combine(dllPath, filename));
var metafilePath = Path.Combine(_pluginPath, "meta.json");
File.WriteAllText(metafilePath, JsonSerializer.Serialize(manifest, _options));
@@ -141,7 +142,7 @@ namespace Jellyfin.Server.Implementations.Tests.Plugins
foreach (var file in files)
{
- File.Create(Path.Combine(_pluginPath, file));
+ FileHelper.CreateEmpty(Path.Combine(_pluginPath, file));
}
var metafilePath = Path.Combine(_pluginPath, "meta.json");
diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs
index 36861294b..c8ae2a88a 100644
--- a/tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs
+++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs
@@ -31,6 +31,7 @@ namespace Jellyfin.Server.Integration.Tests.Controllers
var config = new StartupConfigurationDto()
{
+ ServerName = "NewServer",
UICulture = "NewCulture",
MetadataCountryCode = "be",
PreferredMetadataLanguage = "nl"
@@ -44,7 +45,8 @@ namespace Jellyfin.Server.Integration.Tests.Controllers
Assert.Equal(MediaTypeNames.Application.Json, getResponse.Content.Headers.ContentType?.MediaType);
var newConfig = await getResponse.Content.ReadFromJsonAsync<StartupConfigurationDto>(_jsonOptions);
- Assert.Equal(config.UICulture, newConfig!.UICulture);
+ Assert.Equal(config.ServerName, newConfig!.ServerName);
+ Assert.Equal(config.UICulture, newConfig.UICulture);
Assert.Equal(config.MetadataCountryCode, newConfig.MetadataCountryCode);
Assert.Equal(config.PreferredMetadataLanguage, newConfig.PreferredMetadataLanguage);
}
@@ -88,9 +90,7 @@ namespace Jellyfin.Server.Integration.Tests.Controllers
var newUser = await getResponse.Content.ReadFromJsonAsync<StartupUserDto>(_jsonOptions);
Assert.NotNull(newUser);
Assert.Equal(user.Name, newUser.Name);
- Assert.NotNull(newUser.Password);
- Assert.NotEmpty(newUser.Password);
- Assert.NotEqual(user.Password, newUser.Password);
+ Assert.Null(newUser.Password);
}
[Fact]
diff --git a/tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs b/tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs
index a7fec2960..725e359d7 100644
--- a/tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs
+++ b/tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs
@@ -5,7 +5,9 @@ using System.IO;
using Emby.Server.Implementations;
using Jellyfin.Server.Extensions;
using Jellyfin.Server.Helpers;
+using Jellyfin.Server.ServerSetupApp;
using MediaBrowser.Common;
+using MediaBrowser.Common.Configuration;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
@@ -15,6 +17,7 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Serilog;
+using Serilog.Core;
using Serilog.Extensions.Logging;
namespace Jellyfin.Server.Integration.Tests
@@ -94,7 +97,8 @@ namespace Jellyfin.Server.Integration.Tests
.AddInMemoryCollection(ConfigurationOptions.DefaultConfiguration)
.AddEnvironmentVariables("JELLYFIN_")
.AddInMemoryCollection(commandLineOpts.ConvertToConfig());
- });
+ })
+ .ConfigureServices(e => e.AddSingleton<IStartupLogger, NullStartupLogger>().AddSingleton(e));
}
/// <inheritdoc/>
@@ -103,7 +107,11 @@ namespace Jellyfin.Server.Integration.Tests
var host = builder.Build();
var appHost = (TestAppHost)host.Services.GetRequiredService<IApplicationHost>();
appHost.ServiceProvider = host.Services;
+ var applicationPaths = appHost.ServiceProvider.GetRequiredService<IApplicationPaths>();
+ Program.ApplyStartupMigrationAsync((ServerApplicationPaths)applicationPaths, appHost.ServiceProvider.GetRequiredService<IConfiguration>()).GetAwaiter().GetResult();
+ Program.ApplyCoreMigrationsAsync(appHost.ServiceProvider, Migrations.Stages.JellyfinMigrationStageTypes.CoreInitialisation).GetAwaiter().GetResult();
appHost.InitializeServices(Mock.Of<IConfiguration>()).GetAwaiter().GetResult();
+ Program.ApplyCoreMigrationsAsync(appHost.ServiceProvider, Migrations.Stages.JellyfinMigrationStageTypes.AppInitialisation).GetAwaiter().GetResult();
host.Start();
appHost.RunStartupTasksAsync().GetAwaiter().GetResult();
@@ -123,5 +131,39 @@ namespace Jellyfin.Server.Integration.Tests
base.Dispose(disposing);
}
+
+ private sealed class NullStartupLogger : IStartupLogger
+ {
+ public IStartupLogger BeginGroup(FormattableString logEntry)
+ {
+ return this;
+ }
+
+ public IDisposable? BeginScope<TState>(TState state)
+ where TState : notnull
+ {
+ return NullLogger.Instance.BeginScope(state);
+ }
+
+ public bool IsEnabled(LogLevel logLevel)
+ {
+ return NullLogger.Instance.IsEnabled(logLevel);
+ }
+
+ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
+ {
+ NullLogger.Instance.Log(logLevel, eventId, state, exception, formatter);
+ }
+
+ public Microsoft.Extensions.Logging.ILogger With(Microsoft.Extensions.Logging.ILogger logger)
+ {
+ return this;
+ }
+
+ IStartupLogger IStartupLogger.With(Microsoft.Extensions.Logging.ILogger logger)
+ {
+ return this;
+ }
+ }
}
}
diff --git a/tests/Jellyfin.Server.Integration.Tests/OpenApiSpecTests.cs b/tests/Jellyfin.Server.Integration.Tests/OpenApiSpecTests.cs
index 98195a294..62cdd25ae 100644
--- a/tests/Jellyfin.Server.Integration.Tests/OpenApiSpecTests.cs
+++ b/tests/Jellyfin.Server.Integration.Tests/OpenApiSpecTests.cs
@@ -1,6 +1,7 @@
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
+using MediaBrowser.Model.IO;
using Xunit;
using Xunit.Abstractions;
@@ -33,7 +34,7 @@ namespace Jellyfin.Server.Integration.Tests
// Write out for publishing
string outputPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? ".", "openapi.json"));
_outputHelper.WriteLine("Writing OpenAPI Spec JSON to '{0}'.", outputPath);
- await using var fs = File.Create(outputPath);
+ await using var fs = AsyncFile.Create(outputPath);
await response.Content.CopyToAsync(fs);
}
}